Merge branch 'master' into refactor-jsdoc-types-to-typescript

This commit is contained in:
Mohamed Hegazy authored and GitHub committed 2017-10-12 10:23:21 -07:00
commit 260d37e8ea
90 files changed
+2961 -263

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@ Thank you for submitting a pull request!
Here's a checklist you might find useful.
[ ] There is an associated issue that is labelled
'Bug' or 'Accepting PRs' or is in the Community milestone
'Bug' or 'help wanted' or is in the Community milestone
[ ] Code is up-to-date with the `master` branch
[ ] You've successfully run `jake runtests` locally
[ ] You've signed the CLA
+48 -16
View File
@@ -226,6 +226,23 @@ namespace ts {
return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
},
getApparentType,
getUnionType,
createAnonymousType,
createSignature,
createSymbol,
createIndexInfo,
getAnyType: () => anyType,
getStringType: () => stringType,
getNumberType: () => numberType,
createPromiseType,
createArrayType,
getBooleanType: () => booleanType,
getVoidType: () => voidType,
getUndefinedType: () => undefinedType,
getNullType: () => nullType,
getESSymbolType: () => esSymbolType,
getNeverType: () => neverType,
isSymbolAccessible,
isArrayLikeType,
getAllPossiblePropertiesOfTypes,
getSuggestionForNonexistentProperty: (node, type) => getSuggestionForNonexistentProperty(node, type),
@@ -3675,6 +3692,7 @@ namespace ts {
function buildParameterDisplay(p: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) {
const parameterNode = <ParameterDeclaration>p.valueDeclaration;
if (parameterNode ? isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) {
writePunctuation(writer, SyntaxKind.DotDotDotToken);
}
@@ -6274,7 +6292,7 @@ namespace ts {
}
function getImplicitIndexTypeOfType(type: Type, kind: IndexKind): Type {
if (isObjectLiteralType(type)) {
if (isObjectTypeWithInferableIndex(type)) {
const propTypes: Type[] = [];
for (const prop of getPropertiesOfType(type)) {
if (kind === IndexKind.String || isNumericLiteralName(prop.escapedName)) {
@@ -8289,11 +8307,11 @@ namespace ts {
// The first time an anonymous type is instantiated we compute and store a list of the type
// parameters that are in scope (and therefore potentially referenced). For type literals that
// aren't the right hand side of a generic type alias declaration we optimize by reducing the
// set of type parameters to those that are actually referenced somewhere in the literal.
// set of type parameters to those that are possibly referenced in the literal.
const declaration = symbol.declarations[0];
const outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true) || emptyArray;
typeParameters = symbol.flags & SymbolFlags.TypeLiteral && !target.aliasTypeArguments ?
filter(outerTypeParameters, tp => isTypeParameterReferencedWithin(tp, declaration)) :
filter(outerTypeParameters, tp => isTypeParameterPossiblyReferenced(tp, declaration)) :
outerTypeParameters;
links.typeParameters = typeParameters;
if (typeParameters.length) {
@@ -8319,13 +8337,27 @@ namespace ts {
return type;
}
function isTypeParameterReferencedWithin(tp: TypeParameter, node: Node) {
return tp.isThisType ? forEachChild(node, checkThis) : forEachChild(node, checkIdentifier);
function checkThis(node: Node): boolean {
return node.kind === SyntaxKind.ThisType || forEachChild(node, checkThis);
function isTypeParameterPossiblyReferenced(tp: TypeParameter, node: Node) {
// If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
// between the node and the type parameter declaration, if the node contains actual references to the
// type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
const container = tp.symbol.declarations[0].parent;
if (findAncestor(node, n => n.kind === SyntaxKind.Block ? "quit" : n === container)) {
return forEachChild(node, containsReference);
}
}
function checkIdentifier(node: Node): boolean {
return node.kind === SyntaxKind.Identifier && isPartOfTypeNode(node) && getTypeFromTypeNode(<TypeNode>node) === tp || forEachChild(node, checkIdentifier);
return true;
function containsReference(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ThisType:
return tp.isThisType;
case SyntaxKind.Identifier:
return !tp.isThisType && isPartOfTypeNode(node) && getTypeFromTypeNode(<TypeNode>node) === tp;
case SyntaxKind.TypeQuery:
return true;
}
return forEachChild(node, containsReference);
}
}
@@ -8610,16 +8642,16 @@ namespace ts {
for (let i = 0; i < checkCount; i++) {
const sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source);
const targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target);
const sourceSig = getSingleCallSignature(getNonNullableType(sourceType));
const targetSig = getSingleCallSignature(getNonNullableType(targetType));
// In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
// how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
// they naturally relate only contra-variantly). However, if the source and target parameters both have
// function types with a single call signature, we known we are relating two callback parameters. In
// function types with a single call signature, we know we are relating two callback parameters. In
// that case it is sufficient to only relate the parameters of the signatures co-variantly because,
// similar to return values, callback parameters are output positions. This means that a Promise<T>,
// where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
// with respect to T.
const sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
const targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType));
const callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate &&
(getFalsyFlags(sourceType) & TypeFlags.Nullable) === (getFalsyFlags(targetType) & TypeFlags.Nullable);
const related = callbacks ?
@@ -9831,7 +9863,7 @@ namespace ts {
// if T is related to U.
return kind === IndexKind.String && isRelatedTo(getTemplateTypeFromMappedType(<MappedType>source), targetInfo.type, reportErrors);
}
if (isObjectLiteralType(source)) {
if (isObjectTypeWithInferableIndex(source)) {
let related = Ternary.True;
if (kind === IndexKind.String) {
const sourceNumberInfo = getIndexInfoOfType(source, IndexKind.Number);
@@ -10344,11 +10376,11 @@ namespace ts {
}
/**
* Return true if type was inferred from an object literal or written as an object type literal
* Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
* with no call or construct signatures.
*/
function isObjectLiteralType(type: Type) {
return type.symbol && (type.symbol.flags & (SymbolFlags.ObjectLiteral | SymbolFlags.TypeLiteral)) !== 0 &&
function isObjectTypeWithInferableIndex(type: Type) {
return type.symbol && (type.symbol.flags & (SymbolFlags.ObjectLiteral | SymbolFlags.TypeLiteral | SymbolFlags.ValueModule)) !== 0 &&
getSignaturesOfType(type, SignatureKind.Call).length === 0 &&
getSignaturesOfType(type, SignatureKind.Construct).length === 0;
}
+4 -2
View File
@@ -213,11 +213,13 @@ namespace ts {
return undefined;
}
export function zipWith<T, U>(arrayA: ReadonlyArray<T>, arrayB: ReadonlyArray<U>, callback: (a: T, b: U, index: number) => void): void {
export function zipWith<T, U, V>(arrayA: ReadonlyArray<T>, arrayB: ReadonlyArray<U>, callback: (a: T, b: U, index: number) => V): V[] {
const result: V[] = [];
Debug.assert(arrayA.length === arrayB.length);
for (let i = 0; i < arrayA.length; i++) {
callback(arrayA[i], arrayB[i], i);
result.push(callback(arrayA[i], arrayB[i], i));
}
return result;
}
export function zipToMap<T>(keys: ReadonlyArray<string>, values: ReadonlyArray<T>): Map<T> {
+9 -1
View File
@@ -3681,6 +3681,7 @@
"category": "Message",
"code": 90017
},
"Disable checking for this file.": {
"category": "Message",
"code": 90018
@@ -3725,7 +3726,6 @@
"category": "Message",
"code": 90028
},
"Convert function to an ES2015 class": {
"category": "Message",
"code": 95001
@@ -3765,5 +3765,13 @@
"Annotate with types from JSDoc": {
"category": "Message",
"code": 95010
},
"Infer type of '{0}' from usage.": {
"category": "Message",
"code": 95011
},
"Infer parameter types from usage.": {
"category": "Message",
"code": 95012
}
}
+6 -1
View File
@@ -47,10 +47,15 @@ namespace ts {
* Creates a shallow, memberwise clone of a node with no source map location.
*/
/* @internal */
export function getSynthesizedClone<T extends Node>(node: T | undefined): T {
export function getSynthesizedClone<T extends Node>(node: T | undefined): T | undefined {
// We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
// the original node. We also need to exclude specific properties and only include own-
// properties (to skip members already defined on the shared prototype).
if (node === undefined) {
return undefined;
}
const clone = <T>createSynthesizedNode(node.kind);
clone.flags |= node.flags;
setOriginalNode(clone, node);
+6 -8
View File
@@ -107,7 +107,9 @@ namespace ts {
return {
startRecordingFilesWithChangedResolutions,
finishRecordingFilesWithChangedResolutions,
startCachingPerDirectoryResolution,
// perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
// (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution,
resolveModuleNames,
resolveTypeReferenceDirectives,
@@ -143,8 +145,7 @@ namespace ts {
allFilesHaveInvalidatedResolution = false;
// perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
// (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
perDirectoryResolvedModuleNames.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
clearPerDirectoryResolutions();
}
function startRecordingFilesWithChangedResolutions() {
@@ -168,9 +169,7 @@ namespace ts {
return path => collected && collected.has(path);
}
function startCachingPerDirectoryResolution() {
// perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
// (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
function clearPerDirectoryResolutions() {
perDirectoryResolvedModuleNames.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
}
@@ -184,8 +183,7 @@ namespace ts {
}
});
perDirectoryResolvedModuleNames.clear();
perDirectoryResolvedTypeReferenceDirectives.clear();
clearPerDirectoryResolutions();
}
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
+18
View File
@@ -2695,6 +2695,24 @@ namespace ts {
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
/* @internal */ getBaseConstraintOfType(type: Type): Type | undefined;
/* @internal */ getAnyType(): Type;
/* @internal */ getStringType(): Type;
/* @internal */ getNumberType(): Type;
/* @internal */ getBooleanType(): Type;
/* @internal */ getVoidType(): Type;
/* @internal */ getUndefinedType(): Type;
/* @internal */ getNullType(): Type;
/* @internal */ getESSymbolType(): Type;
/* @internal */ getNeverType(): Type;
/* @internal */ getUnionType(types: Type[], subtypeReduction?: boolean): Type;
/* @internal */ createArrayType(elementType: Type): Type;
/* @internal */ createPromiseType(type: Type): Type;
/* @internal */ createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): Type;
/* @internal */ createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisParameter: Symbol | undefined, parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasLiteralTypes: boolean): Signature;
/* @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol;
/* @internal */ createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo;
/* @internal */ isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult;
/* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined;
/* @internal */ getSymbolWalker(accept?: (symbol: Symbol) => boolean): SymbolWalker;
+8
View File
@@ -5656,6 +5656,14 @@ namespace ts {
return node.kind >= SyntaxKind.FirstJSDocTagNode && node.kind <= SyntaxKind.LastJSDocTagNode;
}
export function isSetAccessor(node: Node): node is SetAccessorDeclaration {
return node.kind === SyntaxKind.SetAccessor;
}
export function isGetAccessor(node: Node): node is GetAccessorDeclaration {
return node.kind === SyntaxKind.GetAccessor;
}
/** True if has jsdoc nodes attached to it. */
/* @internal */
export function hasJSDocNodes(node: Node): node is HasJSDoc {
+172
View File
@@ -360,6 +360,178 @@ function parsePrimaryExpression(): any {
export const j = 10;
export const y = [#|j * j|];
}`);
testExtractFunction("extractFunction_VariableDeclaration_Var", `
[#|var x = 1;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Let_Type", `
[#|let x: number = 1;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Let_NoType", `
[#|let x = 1;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Const_Type", `
[#|const x: number = 1;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Const_NoType", `
[#|const x = 1;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Multiple1", `
[#|const x = 1, y: string = "a";|]
x; y;
`);
testExtractFunction("extractFunction_VariableDeclaration_Multiple2", `
[#|const x = 1, y = "a";
const z = 3;|]
x; y; z;
`);
testExtractFunction("extractFunction_VariableDeclaration_Multiple3", `
[#|const x = 1, y: string = "a";
let z = 3;|]
x; y; z;
`);
testExtractFunction("extractFunction_VariableDeclaration_ConsumedTwice", `
[#|const x: number = 1;|]
x; x;
`);
testExtractFunction("extractFunction_VariableDeclaration_DeclaredTwice", `
[#|var x = 1;
var x = 2;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Var", `
function f() {
let a = 1;
[#|var x = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_NoType", `
function f() {
let a = 1;
[#|let x = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_Type", `
function f() {
let a = 1;
[#|let x: number = 1;
a++;|]
a; x;
}`);
// We propagate numericLiteralFlags, but it's not consumed by the emitter,
// so everything comes out decimal. It would be nice to improve this.
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType1", `
function f() {
let a = 1;
[#|let x: 0o10 | 10 | 0b10 = 10;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType2", `
function f() {
let a = 1;
[#|let x: "a" | 'b' = 'a';
a++;|]
a; x;
}`);
// We propagate numericLiteralFlags, but it's not consumed by the emitter,
// so everything comes out decimal. It would be nice to improve this.
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType1", `
function f() {
let a = 1;
[#|let x: 0o10 | 10 | 0b10 = 10;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_TypeWithComments", `
function f() {
let a = 1;
[#|let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = 'a';
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Const_NoType", `
function f() {
let a = 1;
[#|const x = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Const_Type", `
function f() {
let a = 1;
[#|const x: number = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed1", `
function f() {
let a = 1;
[#|const x = 1;
let y = 2;
a++;|]
a; x; y;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed2", `
function f() {
let a = 1;
[#|var x = 1;
let y = 2;
a++;|]
a; x; y;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed3", `
function f() {
let a = 1;
[#|let x: number = 1;
let y = 2;
a++;|]
a; x; y;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_UnionUndefined", `
function f() {
let a = 1;
[#|let x: number | undefined = 1;
let y: undefined | number = 2;
let z: (undefined | number) = 3;
a++;|]
a; x; y; z;
}`);
testExtractFunction("extractFunction_VariableDeclaration_ShorthandProperty", `
function f() {
[#|let x;|]
return { x };
}`);
});
function testExtractFunction(caption: string, text: string) {
+12 -68
View File
@@ -5,9 +5,9 @@ namespace ts.projectSystem {
describe("project telemetry", () => {
it("does nothing for inferred project", () => {
const file = makeFile("/a.js");
const et = new EventTracker([file]);
const et = new TestServerEventManager([file]);
et.service.openClientFile(file.path);
assert.equal(et.getEvents().length, 0);
et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent);
});
it("only sends an event once", () => {
@@ -15,7 +15,7 @@ namespace ts.projectSystem {
const file2 = makeFile("/b.ts");
const tsconfig = makeFile("/a/tsconfig.json", {});
const et = new EventTracker([file, file2, tsconfig]);
const et = new TestServerEventManager([file, file2, tsconfig]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({}, tsconfig.path);
@@ -25,12 +25,12 @@ namespace ts.projectSystem {
et.service.openClientFile(file2.path);
checkNumberOfProjects(et.service, { inferredProjects: 1 });
assert.equal(et.getEvents().length, 0);
et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent);
et.service.openClientFile(file.path);
checkNumberOfProjects(et.service, { configuredProjects: 1, inferredProjects: 1 });
assert.equal(et.getEvents().length, 0);
et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent);
});
it("counts files by extension", () => {
@@ -39,7 +39,7 @@ namespace ts.projectSystem {
const compilerOptions: ts.CompilerOptions = { allowJs: true };
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, include: ["src"] });
const et = new EventTracker([...files, notIncludedFile, tsconfig]);
const et = new TestServerEventManager([...files, notIncludedFile, tsconfig]);
et.service.openClientFile(files[0].path);
et.assertProjectInfoTelemetryEvent({
fileStats: { ts: 2, tsx: 1, js: 1, jsx: 1, dts: 1 },
@@ -50,7 +50,7 @@ namespace ts.projectSystem {
it("works with external project", () => {
const file1 = makeFile("/a.ts");
const et = new EventTracker([file1]);
const et = new TestServerEventManager([file1]);
const compilerOptions: ts.server.protocol.CompilerOptions = { strict: true };
const projectFileName = "/hunter2/foo.csproj";
@@ -148,7 +148,7 @@ namespace ts.projectSystem {
(compilerOptions as any).unknownCompilerOption = "hunter2"; // These are always ignored.
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, files: ["/a.ts"] });
const et = new EventTracker([file, tsconfig]);
const et = new TestServerEventManager([file, tsconfig]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
@@ -168,7 +168,7 @@ namespace ts.projectSystem {
compileOnSave: true,
});
const et = new EventTracker([tsconfig, file]);
const et = new TestServerEventManager([tsconfig, file]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
extends: true,
@@ -198,7 +198,7 @@ namespace ts.projectSystem {
exclude: [],
},
});
const et = new EventTracker([jsconfig, file]);
const et = new TestServerEventManager([jsconfig, file]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
projectId: Harness.mockHash("/jsconfig.json"),
@@ -216,10 +216,10 @@ namespace ts.projectSystem {
it("detects whether language service was disabled", () => {
const file = makeFile("/a.js");
const tsconfig = makeFile("/jsconfig.json", {});
const et = new EventTracker([tsconfig, file]);
const et = new TestServerEventManager([tsconfig, file]);
et.host.getFileSize = () => server.maxProgramSizeForNonTsFiles + 1;
et.service.openClientFile(file.path);
et.getEvent<server.ProjectLanguageServiceStateEvent>(server.ProjectLanguageServiceStateEvent, /*mayBeMore*/ true);
et.getEvent<server.ProjectLanguageServiceStateEvent>(server.ProjectLanguageServiceStateEvent);
et.assertProjectInfoTelemetryEvent({
projectId: Harness.mockHash("/jsconfig.json"),
fileStats: fileStats({ js: 1 }),
@@ -235,63 +235,7 @@ namespace ts.projectSystem {
});
});
class EventTracker {
private events: server.ProjectServiceEvent[] = [];
readonly service: TestProjectService;
readonly host: projectSystem.TestServerHost;
constructor(files: projectSystem.FileOrFolder[]) {
this.host = createServerHost(files);
this.service = createProjectService(this.host, {
eventHandler: event => {
this.events.push(event);
},
});
}
getEvents(): ReadonlyArray<server.ProjectServiceEvent> {
const events = this.events;
this.events = [];
return events;
}
assertProjectInfoTelemetryEvent(partial: Partial<server.ProjectInfoTelemetryEventData>, configFile?: string): void {
assert.deepEqual(this.getEvent<server.ProjectInfoTelemetryEvent>(ts.server.ProjectInfoTelemetryEvent), {
projectId: Harness.mockHash(configFile || "/tsconfig.json"),
fileStats: fileStats({ ts: 1 }),
compilerOptions: {},
extends: false,
files: false,
include: false,
exclude: false,
compileOnSave: false,
typeAcquisition: {
enable: false,
exclude: false,
include: false,
},
configFileName: "tsconfig.json",
projectType: "configured",
languageServiceEnabled: true,
version: ts.version,
...partial,
});
}
getEvent<T extends server.ProjectServiceEvent>(eventName: T["eventName"], mayBeMore = false): T["data"] {
if (mayBeMore) { assert(this.events.length !== 0); }
else { assert.equal(this.events.length, 1); }
const event = this.events.shift();
assert.equal(event.eventName, eventName);
return event.data;
}
}
function makeFile(path: string, content: {} = ""): projectSystem.FileOrFolder {
return { path, content: isString(content) ? "" : JSON.stringify(content) };
}
function fileStats(nonZeroStats: Partial<server.FileStats>): server.FileStats {
return { ts: 0, tsx: 0, dts: 0, js: 0, jsx: 0, ...nonZeroStats };
}
}
+176 -49
View File
@@ -132,16 +132,77 @@ namespace ts.projectSystem {
return map(fileNames, toExternalFile);
}
class TestServerEventManager {
public events: server.ProjectServiceEvent[] = [];
export function fileStats(nonZeroStats: Partial<server.FileStats>): server.FileStats {
return { ts: 0, tsx: 0, dts: 0, js: 0, jsx: 0, ...nonZeroStats };
}
handler: server.ProjectServiceEventHandler = (event: server.ProjectServiceEvent) => {
this.events.push(event);
export class TestServerEventManager {
private events: server.ProjectServiceEvent[] = [];
readonly session: TestSession;
readonly service: server.ProjectService;
readonly host: projectSystem.TestServerHost;
constructor(files: projectSystem.FileOrFolder[]) {
this.host = createServerHost(files);
this.session = createSession(this.host, {
canUseEvents: true,
eventHandler: event => this.events.push(event),
});
this.service = this.session.getProjectService();
}
checkEventCountOfType(eventType: "configFileDiag", expectedCount: number) {
const eventsOfType = filter(this.events, e => e.eventName === eventType);
assert.equal(eventsOfType.length, expectedCount, `The actual event counts of type ${eventType} is ${eventsOfType.length}, while expected ${expectedCount}`);
getEvents(): ReadonlyArray<server.ProjectServiceEvent> {
const events = this.events;
this.events = [];
return events;
}
getEvent<T extends server.ProjectServiceEvent>(eventName: T["eventName"]): T["data"] {
let eventData: T["data"];
filterMutate(this.events, e => {
if (e.eventName === eventName) {
if (eventData !== undefined) {
assert(false, "more than one event found");
}
eventData = e.data;
return false;
}
return true;
});
assert.isDefined(eventData);
return eventData;
}
hasZeroEvent<T extends server.ProjectServiceEvent>(eventName: T["eventName"]) {
this.events.forEach(event => assert.notEqual(event.eventName, eventName));
}
checkSingleConfigFileDiagEvent(configFileName: string, triggerFile: string) {
const eventData = this.getEvent<server.ConfigFileDiagEvent>(server.ConfigFileDiagEvent);
assert.equal(eventData.configFileName, configFileName);
assert.equal(eventData.triggerFile, triggerFile);
}
assertProjectInfoTelemetryEvent(partial: Partial<server.ProjectInfoTelemetryEventData>, configFile?: string): void {
assert.deepEqual(this.getEvent<server.ProjectInfoTelemetryEvent>(ts.server.ProjectInfoTelemetryEvent), {
projectId: Harness.mockHash(configFile || "/tsconfig.json"),
fileStats: fileStats({ ts: 1 }),
compilerOptions: {},
extends: false,
files: false,
include: false,
exclude: false,
compileOnSave: false,
typeAcquisition: {
enable: false,
exclude: false,
include: false,
},
configFileName: "tsconfig.json",
projectType: "configured",
languageServiceEnabled: true,
version: ts.version,
...partial,
});
}
}
@@ -461,7 +522,7 @@ namespace ts.projectSystem {
const { configFileName, configFileErrors } = projectService.openClientFile(file1.path);
assert(configFileName, "should find config file");
assert.isTrue(!configFileErrors, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`);
assert.isTrue(!configFileErrors || configFileErrors.length === 0, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`);
checkNumberOfInferredProjects(projectService, 0);
checkNumberOfConfiguredProjects(projectService, 1);
@@ -501,7 +562,7 @@ namespace ts.projectSystem {
const { configFileName, configFileErrors } = projectService.openClientFile(file1.path);
assert(configFileName, "should find config file");
assert.isTrue(!configFileErrors, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`);
assert.isTrue(!configFileErrors || configFileErrors.length === 0, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`);
checkNumberOfInferredProjects(projectService, 0);
checkNumberOfConfiguredProjects(projectService, 1);
@@ -2917,6 +2978,52 @@ namespace ts.projectSystem {
function checkSnapLength(snap: IScriptSnapshot, expectedLength: number) {
assert.equal(snap.getLength(), expectedLength, "Incorrect snapshot size");
}
function verifyOpenFileWorks(useCaseSensitiveFileNames: boolean) {
const file1: FileOrFolder = {
path: "/a/b/src/app.ts",
content: "let x = 10;"
};
const file2: FileOrFolder = {
path: "/a/B/lib/module2.ts",
content: "let z = 10;"
};
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: ""
};
const configFile2: FileOrFolder = {
path: "/a/tsconfig.json",
content: ""
};
const host = createServerHost([file1, file2, configFile, configFile2], {
useCaseSensitiveFileNames
});
const service = createProjectService(host);
// Open file1 -> configFile
verifyConfigFileName(file1, "/a", configFile);
verifyConfigFileName(file1, "/a/b", configFile);
verifyConfigFileName(file1, "/a/B", useCaseSensitiveFileNames ? undefined : configFile);
// Open file2 use root "/a/b"
verifyConfigFileName(file2, "/a", useCaseSensitiveFileNames ? configFile2 : configFile);
verifyConfigFileName(file2, "/a/b", useCaseSensitiveFileNames ? undefined : configFile);
verifyConfigFileName(file2, "/a/B", useCaseSensitiveFileNames ? undefined : configFile);
function verifyConfigFileName(file: FileOrFolder, projectRoot: string, expectedConfigFile: FileOrFolder | undefined) {
const { configFileName } = service.openClientFile(file.path, /*fileContent*/ undefined, /*scriptKind*/ undefined, projectRoot);
assert.equal(configFileName, expectedConfigFile && expectedConfigFile.path);
service.closeClientFile(file.path);
}
}
it("works when project root is used with case-sensitive system", () => {
verifyOpenFileWorks(/*useCaseSensitiveFileNames*/ true);
});
it("works when project root is used with case-insensitive system", () => {
verifyOpenFileWorks(/*useCaseSensitiveFileNames*/ false);
});
});
describe("Language service", () => {
@@ -3113,7 +3220,6 @@ namespace ts.projectSystem {
describe("Configure file diagnostics events", () => {
it("are generated when the config file has errors", () => {
const serverEventManager = new TestServerEventManager();
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
@@ -3127,26 +3233,12 @@ namespace ts.projectSystem {
}
}`
};
const host = createServerHost([file, configFile]);
const session = createSession(host, {
canUseEvents: true,
eventHandler: serverEventManager.handler
});
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
for (const event of serverEventManager.events) {
if (event.eventName === "configFileDiag") {
assert.equal(event.data.configFileName, configFile.path);
assert.equal(event.data.triggerFile, file.path);
return;
}
}
const serverEventManager = new TestServerEventManager([file, configFile]);
openFilesForSession([file], serverEventManager.session);
serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path);
});
it("are generated when the config file doesn't have errors", () => {
const serverEventManager = new TestServerEventManager();
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
@@ -3157,18 +3249,12 @@ namespace ts.projectSystem {
"compilerOptions": {}
}`
};
const host = createServerHost([file, configFile]);
const session = createSession(host, {
canUseEvents: true,
eventHandler: serverEventManager.handler
});
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
const serverEventManager = new TestServerEventManager([file, configFile]);
openFilesForSession([file], serverEventManager.session);
serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path);
});
it("are generated when the config file changes", () => {
const serverEventManager = new TestServerEventManager();
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
@@ -3180,29 +3266,70 @@ namespace ts.projectSystem {
}`
};
const host = createServerHost([file, configFile]);
const session = createSession(host, {
canUseEvents: true,
eventHandler: serverEventManager.handler
});
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
const serverEventManager = new TestServerEventManager([file, configFile]);
openFilesForSession([file], serverEventManager.session);
serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, file.path);
configFile.content = `{
"compilerOptions": {
"haha": 123
}
}`;
host.reloadFS([file, configFile]);
host.runQueuedTimeoutCallbacks();
serverEventManager.checkEventCountOfType("configFileDiag", 2);
serverEventManager.host.reloadFS([file, configFile]);
serverEventManager.host.runQueuedTimeoutCallbacks();
serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, configFile.path);
configFile.content = `{
"compilerOptions": {}
}`;
host.reloadFS([file, configFile]);
host.runQueuedTimeoutCallbacks();
serverEventManager.checkEventCountOfType("configFileDiag", 3);
serverEventManager.host.reloadFS([file, configFile]);
serverEventManager.host.runQueuedTimeoutCallbacks();
serverEventManager.checkSingleConfigFileDiagEvent(configFile.path, configFile.path);
});
it("are not generated when the config file doesnot include file opened and config file has errors", () => {
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
};
const file2 = {
path: "/a/b/test.ts",
content: "let x = 10"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {
"foo": "bar",
"allowJS": true
},
"files": ["app.ts"]
}`
};
const serverEventManager = new TestServerEventManager([file, file2, libFile, configFile]);
openFilesForSession([file2], serverEventManager.session);
serverEventManager.hasZeroEvent("configFileDiag");
});
it("are not generated when the config file doesnot include file opened and doesnt contain any errors", () => {
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
};
const file2 = {
path: "/a/b/test.ts",
content: "let x = 10"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"files": ["app.ts"]
}`
};
const serverEventManager = new TestServerEventManager([file, file2, libFile, configFile]);
openFilesForSession([file2], serverEventManager.session);
serverEventManager.hasZeroEvent("configFileDiag");
});
});
+18 -10
View File
@@ -1218,7 +1218,7 @@ namespace ts.server {
projectRootPath?: NormalizedPath) {
let searchPath = asNormalizedPath(getDirectoryPath(info.fileName));
while (!projectRootPath || stringContains(searchPath, projectRootPath)) {
while (!projectRootPath || containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) {
const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json"));
let result = action(tsconfigFileName, combinePaths(canonicalSearchPath, "tsconfig.json"));
@@ -1579,14 +1579,17 @@ namespace ts.server {
project.watchWildcards(projectOptions.wildcardDirectories);
}
this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave);
this.sendConfigFileDiagEvent(project, configFileName);
}
private sendConfigFileDiagEvent(project: ConfiguredProject, triggerFile: NormalizedPath) {
if (!this.eventHandler) {
return;
}
this.eventHandler(<ConfigFileDiagEvent>{
eventName: ConfigFileDiagEvent,
data: { configFileName, diagnostics: project.getGlobalProjectErrors() || [], triggerFile: configFileName }
data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile }
});
}
@@ -1907,6 +1910,7 @@ namespace ts.server {
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult {
let configFileName: NormalizedPath;
let sendConfigFileDiagEvent = false;
let configFileErrors: ReadonlyArray<Diagnostic>;
const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent);
@@ -1917,14 +1921,8 @@ namespace ts.server {
project = this.findConfiguredProjectByProjectName(configFileName);
if (!project) {
project = this.createConfiguredProject(configFileName);
// even if opening config file was successful, it could still
// contain errors that were tolerated.
const errors = project.getGlobalProjectErrors();
if (errors && errors.length > 0) {
// set configFileErrors only when the errors array is non-empty
configFileErrors = errors;
}
// Send the event only if the project got created as part of this open request
sendConfigFileDiagEvent = true;
}
}
}
@@ -1938,10 +1936,19 @@ namespace ts.server {
// At this point if file is part of any any configured or external project, then it would be present in the containing projects
// So if it still doesnt have any containing projects, it needs to be part of inferred project
if (info.isOrphan()) {
// Since the file isnt part of configured project, do not send config file event
configFileName = undefined;
sendConfigFileDiagEvent = false;
this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
}
this.addToListOfOpenFiles(info);
if (sendConfigFileDiagEvent) {
configFileErrors = project.getAllProjectErrors();
this.sendConfigFileDiagEvent(project as ConfiguredProject, fileName);
}
// Remove the configured projects that have zero references from open files.
// This was postponed from closeOpenFile to after opening next file,
// so that we can reuse the project if we need to right away
@@ -1957,6 +1964,7 @@ namespace ts.server {
// the file from that old project is reopened because of opening file from here.
this.deleteOrphanScriptInfoNotInAnyProject();
this.printProjects();
return { configFileName, configFileErrors };
}
+4 -2
View File
@@ -1271,14 +1271,14 @@ namespace ts.server {
* Get the errors that dont have any file name associated
*/
getGlobalProjectErrors(): ReadonlyArray<Diagnostic> {
return filter(this.projectErrors, diagnostic => !diagnostic.file);
return filter(this.projectErrors, diagnostic => !diagnostic.file) || emptyArray;
}
/**
* Get all the project errors
*/
getAllProjectErrors(): ReadonlyArray<Diagnostic> {
return this.projectErrors;
return this.projectErrors || emptyArray;
}
setProjectErrors(projectErrors: Diagnostic[]) {
@@ -1333,6 +1333,8 @@ namespace ts.server {
}
this.stopWatchingWildCards();
this.projectErrors = undefined;
this.configFileSpecs = undefined;
super.close();
}
+1 -7
View File
@@ -969,13 +969,7 @@ namespace ts.server {
* @param fileContent is a version of the file content that is known to be more up to date than the one on disk
*/
private openClientFile(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: NormalizedPath) {
const { configFileName, configFileErrors } = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath);
if (this.eventHandler) {
this.eventHandler({
eventName: "configFileDiag",
data: { triggerFile: fileName, configFileName, diagnostics: configFileErrors || emptyArray }
});
}
this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath);
}
private getPosition(args: protocol.FileLocationRequestArgs, scriptInfo: ScriptInfo): number {
@@ -68,10 +68,14 @@ namespace ts.server.typingsInstaller {
return combinePaths(normalizeSlashes(globalTypingsCacheLocation), `node_modules/${TypesRegistryPackageName}/index.json`);
}
type ExecSync = (command: string, options: { cwd: string, stdio?: "ignore" }) => any;
interface ExecSyncOptions {
cwd: string;
encoding: "utf-8";
}
type ExecSync = (command: string, options: ExecSyncOptions) => string;
export class NodeTypingsInstaller extends TypingsInstaller {
private readonly execSync: ExecSync;
private readonly nodeExecSync: ExecSync;
private readonly npmPath: string;
readonly typesRegistry: Map<void>;
@@ -95,7 +99,7 @@ namespace ts.server.typingsInstaller {
this.log.writeLine(`Process id: ${process.pid}`);
this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`);
}
({ execSync: this.execSync } = require("child_process"));
({ execSync: this.nodeExecSync } = require("child_process"));
this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
@@ -103,7 +107,7 @@ namespace ts.server.typingsInstaller {
if (this.log.isEnabled()) {
this.log.writeLine(`Updating ${TypesRegistryPackageName} npm package...`);
}
this.execSync(`${this.npmPath} install --ignore-scripts ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation, stdio: "ignore" });
this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation });
if (this.log.isEnabled()) {
this.log.writeLine(`Updated ${TypesRegistryPackageName} npm package`);
}
@@ -155,22 +159,31 @@ namespace ts.server.typingsInstaller {
}
const command = `${this.npmPath} install --ignore-scripts ${args.join(" ")} --save-dev --user-agent="typesInstaller/${version}"`;
const start = Date.now();
let stdout: Buffer;
let stderr: Buffer;
let hasError = false;
try {
stdout = this.execSync(command, { cwd });
}
catch (e) {
stdout = e.stdout;
stderr = e.stderr;
hasError = true;
}
const hasError = this.execSyncAndLog(command, { cwd });
if (this.log.isEnabled()) {
this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms${sys.newLine}stdout: ${stdout && stdout.toString()}${sys.newLine}stderr: ${stderr && stderr.toString()}`);
this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`);
}
onRequestCompleted(!hasError);
}
/** Returns 'true' in case of error. */
private execSyncAndLog(command: string, options: Pick<ExecSyncOptions, "cwd">): boolean {
if (this.log.isEnabled()) {
this.log.writeLine(`Exec: ${command}`);
}
try {
const stdout = this.nodeExecSync(command, { ...options, encoding: "utf-8" });
if (this.log.isEnabled()) {
this.log.writeLine(` Succeeded. stdout:${indent(sys.newLine, stdout)}`);
}
return false;
}
catch (error) {
const { stdout, stderr } = error;
this.log.writeLine(` Failed. stdout:${indent(sys.newLine, stdout)}${sys.newLine} stderr:${indent(sys.newLine, stderr)}`);
return true;
}
}
}
const logFilePath = findArgument(server.Arguments.LogFile);
@@ -193,4 +206,8 @@ namespace ts.server.typingsInstaller {
});
const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, /*throttleLimit*/5, log);
installer.listen();
function indent(newline: string, string: string): string {
return `${newline} ` + string.replace(/\r?\n/, `${newline} `);
}
}
+1
View File
@@ -13,3 +13,4 @@
/// <reference path='importFixes.ts' />
/// <reference path='disableJsDiagnostics.ts' />
/// <reference path='helpers.ts' />
/// <reference path='inferFromUsage.ts' />
+653
View File
@@ -0,0 +1,653 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: [
// Variable declarations
Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
// Variable uses
Diagnostics.Variable_0_implicitly_has_an_1_type.code,
// Parameter declarations
Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
// Get Accessor declarations
Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
// Set Accessor declarations
Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
// Property declarations
Diagnostics.Member_0_implicitly_has_an_1_type.code,
],
getCodeActions: getActionsForAddExplicitTypeAnnotation
});
function getActionsForAddExplicitTypeAnnotation({ sourceFile, program, span: { start }, errorCode, cancellationToken }: CodeFixContext): CodeAction[] | undefined {
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
let writer: StringSymbolWriter;
if (isInJavaScriptFile(token)) {
return undefined;
}
switch (token.kind) {
case SyntaxKind.Identifier:
case SyntaxKind.DotDotDotToken:
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
// Allowed
break;
default:
return undefined;
}
const containingFunction = getContainingFunction(token);
const checker = program.getTypeChecker();
switch (errorCode) {
// Variable and Property declarations
case Diagnostics.Member_0_implicitly_has_an_1_type.code:
case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
return getCodeActionForVariableDeclaration(<PropertyDeclaration | PropertySignature | VariableDeclaration>token.parent);
case Diagnostics.Variable_0_implicitly_has_an_1_type.code:
return getCodeActionForVariableUsage(<Identifier>token);
// Parameter declarations
case Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
if (isSetAccessor(containingFunction)) {
return getCodeActionForSetAccessor(containingFunction);
}
// falls through
case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
return getCodeActionForParameters(<ParameterDeclaration>token.parent);
// Get Accessor declarations
case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
return isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined;
// Set Accessor declarations
case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
return isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined;
}
return undefined;
function getCodeActionForVariableDeclaration(declaration: VariableDeclaration | PropertyDeclaration | PropertySignature) {
if (!isIdentifier(declaration.name)) {
return undefined;
}
const type = inferTypeForVariableFromUsage(declaration.name);
const typeString = type && typeToString(type, declaration);
if (!typeString) {
return undefined;
}
return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), `: ${typeString}`);
}
function getCodeActionForVariableUsage(token: Identifier) {
const symbol = checker.getSymbolAtLocation(token);
return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(<VariableDeclaration>symbol.valueDeclaration);
}
function isApplicableFunctionForInference(declaration: FunctionLike): declaration is MethodDeclaration | FunctionDeclaration | ConstructorDeclaration {
switch (declaration.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.Constructor:
return true;
case SyntaxKind.FunctionExpression:
return !!(declaration as FunctionExpression).name;
}
return false;
}
function getCodeActionForParameters(parameterDeclaration: ParameterDeclaration): CodeAction[] {
if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) {
return undefined;
}
const types = inferTypeForParametersFromUsage(containingFunction) ||
map(containingFunction.parameters, p => isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name));
if (!types) {
return undefined;
}
const textChanges: TextChange[] = zipWith(containingFunction.parameters, types, (parameter, type) => {
if (type && !parameter.type && !parameter.initializer) {
const typeString = typeToString(type, containingFunction);
return typeString ? {
span: { start: parameter.end, length: 0 },
newText: `: ${typeString}`
} : undefined;
}
}).filter(c => !!c);
return textChanges.length ? [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]),
changes: [{
fileName: sourceFile.fileName,
textChanges
}]
}] : undefined;
}
function getCodeActionForSetAccessor(setAccessorDeclaration: SetAccessorDeclaration) {
const setAccessorParameter = setAccessorDeclaration.parameters[0];
if (!setAccessorParameter || !isIdentifier(setAccessorDeclaration.name) || !isIdentifier(setAccessorParameter.name)) {
return undefined;
}
const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) ||
inferTypeForVariableFromUsage(setAccessorParameter.name);
const typeString = type && typeToString(type, containingFunction);
if (!typeString) {
return undefined;
}
return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), `: ${typeString}`);
}
function getCodeActionForGetAccessor(getAccessorDeclaration: GetAccessorDeclaration) {
if (!isIdentifier(getAccessorDeclaration.name)) {
return undefined;
}
const type = inferTypeForVariableFromUsage(getAccessorDeclaration.name);
const typeString = type && typeToString(type, containingFunction);
if (!typeString) {
return undefined;
}
const closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, SyntaxKind.CloseParenToken);
return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), `: ${typeString}`);
}
function createCodeActions(name: string, start: number, typeString: string) {
return [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Infer_type_of_0_from_usage), [name]),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{
span: { start, length: 0 },
newText: typeString
}]
}]
}];
}
function getReferences(token: PropertyName | Token<SyntaxKind.ConstructorKeyword>) {
const references = FindAllReferences.findReferencedSymbols(
program,
cancellationToken,
program.getSourceFiles(),
token.getSourceFile(),
token.getStart());
Debug.assert(!!references, "Found no references!");
Debug.assert(references.length === 1, "Found more references than expected");
return map(references[0].references, r => <Identifier>getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false));
}
function inferTypeForVariableFromUsage(token: Identifier) {
return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken);
}
function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration) {
switch (containingFunction.kind) {
case SyntaxKind.Constructor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
const isConstructor = containingFunction.kind === SyntaxKind.Constructor;
const searchToken = isConstructor ?
<Token<SyntaxKind.ConstructorKeyword>>getFirstChildOfKind(containingFunction, sourceFile, SyntaxKind.ConstructorKeyword) :
containingFunction.name;
if (searchToken) {
return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken);
}
}
}
function getTypeAccessiblityWriter() {
if (!writer) {
let str = "";
let typeIsAccessible = true;
const writeText: (text: string) => void = text => str += text;
writer = {
string: () => typeIsAccessible ? str : undefined,
writeKeyword: writeText,
writeOperator: writeText,
writePunctuation: writeText,
writeSpace: writeText,
writeStringLiteral: writeText,
writeParameter: writeText,
writeProperty: writeText,
writeSymbol: writeText,
writeLine: () => str += " ",
increaseIndent: noop,
decreaseIndent: noop,
clear: () => { str = ""; typeIsAccessible = true; },
trackSymbol: (symbol, declaration, meaning) => {
if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== SymbolAccessibility.Accessible) {
typeIsAccessible = false;
}
},
reportInaccessibleThisError: () => { typeIsAccessible = false; },
reportPrivateInBaseOfClassExpression: () => { typeIsAccessible = false; },
};
}
writer.clear();
return writer;
}
function typeToString(type: Type, enclosingDeclaration: Declaration) {
const writer = getTypeAccessiblityWriter();
checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration);
return writer.string();
}
function getFirstChildOfKind(node: Node, sourcefile: SourceFile, kind: SyntaxKind) {
for (const child of node.getChildren(sourcefile)) {
if (child.kind === kind) return child;
}
return undefined;
}
}
namespace InferFromReference {
interface CallContext {
argumentTypes: Type[];
returnType: UsageContext;
}
interface UsageContext {
isNumber?: boolean;
isString?: boolean;
isNumberOrString?: boolean;
candidateTypes?: Type[];
properties?: UnderscoreEscapedMap<UsageContext>;
callContexts?: CallContext[];
constructContexts?: CallContext[];
numberIndexContext?: UsageContext;
stringIndexContext?: UsageContext;
}
export function inferTypeFromReferences(references: Identifier[], checker: TypeChecker, cancellationToken: CancellationToken): Type | undefined {
const usageContext: UsageContext = {};
for (const reference of references) {
cancellationToken.throwIfCancellationRequested();
inferTypeFromContext(reference, checker, usageContext);
}
return getTypeFromUsageContext(usageContext, checker);
}
export function inferTypeForParametersFromReferences(references: Identifier[], declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): (Type | undefined)[] | undefined {
if (declaration.parameters) {
const usageContext: UsageContext = {};
for (const reference of references) {
cancellationToken.throwIfCancellationRequested();
inferTypeFromContext(reference, checker, usageContext);
}
const isConstructor = declaration.kind === SyntaxKind.Constructor;
const callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts;
if (callContexts) {
const paramTypes: Type[] = [];
for (let parameterIndex = 0; parameterIndex < declaration.parameters.length; parameterIndex++) {
let types: Type[] = [];
const isRestParameter = ts.isRestParameter(declaration.parameters[parameterIndex]);
for (const callContext of callContexts) {
if (callContext.argumentTypes.length > parameterIndex) {
if (isRestParameter) {
types = concatenate(types, map(callContext.argumentTypes.slice(parameterIndex), a => checker.getBaseTypeOfLiteralType(a)));
}
else {
types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex]));
}
}
}
if (types.length) {
const type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true));
paramTypes[parameterIndex] = isRestParameter ? checker.createArrayType(type) : type;
}
}
return paramTypes;
}
}
return undefined;
}
function inferTypeFromContext(node: Expression, checker: TypeChecker, usageContext: UsageContext): void {
while (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
node = <Expression>node.parent;
}
switch (node.parent.kind) {
case SyntaxKind.PostfixUnaryExpression:
usageContext.isNumber = true;
break;
case SyntaxKind.PrefixUnaryExpression:
inferTypeFromPrefixUnaryExpressionContext(<PrefixUnaryExpression>node.parent, usageContext);
break;
case SyntaxKind.BinaryExpression:
inferTypeFromBinaryExpressionContext(node, <BinaryExpression>node.parent, checker, usageContext);
break;
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
inferTypeFromSwitchStatementLabelContext(<CaseOrDefaultClause>node.parent, checker, usageContext);
break;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
if ((<CallExpression | NewExpression>node.parent).expression === node) {
inferTypeFromCallExpressionContext(<CallExpression | NewExpression>node.parent, checker, usageContext);
}
else {
inferTypeFromContextualType(node, checker, usageContext);
}
break;
case SyntaxKind.PropertyAccessExpression:
inferTypeFromPropertyAccessExpressionContext(<PropertyAccessExpression>node.parent, checker, usageContext);
break;
case SyntaxKind.ElementAccessExpression:
inferTypeFromPropertyElementExpressionContext(<ElementAccessExpression>node.parent, node, checker, usageContext);
break;
default:
return inferTypeFromContextualType(node, checker, usageContext);
}
}
function inferTypeFromContextualType(node: Expression, checker: TypeChecker, usageContext: UsageContext): void {
if (isPartOfExpression(node)) {
addCandidateType(usageContext, checker.getContextualType(node));
}
}
function inferTypeFromPrefixUnaryExpressionContext(node: PrefixUnaryExpression, usageContext: UsageContext): void {
switch (node.operator) {
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
usageContext.isNumber = true;
break;
case SyntaxKind.PlusToken:
usageContext.isNumberOrString = true;
break;
// case SyntaxKind.ExclamationToken:
// no inferences here;
}
}
function inferTypeFromBinaryExpressionContext(node: Expression, parent: BinaryExpression, checker: TypeChecker, usageContext: UsageContext): void {
switch (parent.operatorToken.kind) {
// ExponentiationOperator
case SyntaxKind.AsteriskAsteriskToken:
// MultiplicativeOperator
case SyntaxKind.AsteriskToken:
case SyntaxKind.SlashToken:
case SyntaxKind.PercentToken:
// ShiftOperator
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
// BitwiseOperator
case SyntaxKind.AmpersandToken:
case SyntaxKind.BarToken:
case SyntaxKind.CaretToken:
// CompoundAssignmentOperator
case SyntaxKind.MinusEqualsToken:
case SyntaxKind.AsteriskAsteriskEqualsToken:
case SyntaxKind.AsteriskEqualsToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.PercentEqualsToken:
case SyntaxKind.AmpersandEqualsToken:
case SyntaxKind.BarEqualsToken:
case SyntaxKind.CaretEqualsToken:
case SyntaxKind.LessThanLessThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
// AdditiveOperator
case SyntaxKind.MinusToken:
// RelationalOperator
case SyntaxKind.LessThanToken:
case SyntaxKind.LessThanEqualsToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.GreaterThanEqualsToken:
const operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
if (operandType.flags & TypeFlags.EnumLike) {
addCandidateType(usageContext, operandType);
}
else {
usageContext.isNumber = true;
}
break;
case SyntaxKind.PlusEqualsToken:
case SyntaxKind.PlusToken:
const otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
if (otherOperandType.flags & TypeFlags.EnumLike) {
addCandidateType(usageContext, otherOperandType);
}
else if (otherOperandType.flags & TypeFlags.NumberLike) {
usageContext.isNumber = true;
}
else if (otherOperandType.flags & TypeFlags.StringLike) {
usageContext.isString = true;
}
else {
usageContext.isNumberOrString = true;
}
break;
// AssignmentOperators
case SyntaxKind.EqualsToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
addCandidateType(usageContext, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left));
break;
case SyntaxKind.InKeyword:
if (node === parent.left) {
usageContext.isString = true;
}
break;
// LogicalOperator
case SyntaxKind.BarBarToken:
if (node === parent.left &&
(node.parent.parent.kind === SyntaxKind.VariableDeclaration || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
// var x = x || {};
// TODO: use getFalsyflagsOfType
addCandidateType(usageContext, checker.getTypeAtLocation(parent.right));
}
break;
case SyntaxKind.AmpersandAmpersandToken:
case SyntaxKind.CommaToken:
case SyntaxKind.InstanceOfKeyword:
// nothing to infer here
break;
}
}
function inferTypeFromSwitchStatementLabelContext(parent: CaseOrDefaultClause, checker: TypeChecker, usageContext: UsageContext): void {
addCandidateType(usageContext, checker.getTypeAtLocation((<SwitchStatement>parent.parent.parent).expression));
}
function inferTypeFromCallExpressionContext(parent: CallExpression | NewExpression, checker: TypeChecker, usageContext: UsageContext): void {
const callContext: CallContext = {
argumentTypes: [],
returnType: {}
};
if (parent.arguments) {
for (const argument of parent.arguments) {
callContext.argumentTypes.push(checker.getTypeAtLocation(argument));
}
}
inferTypeFromContext(parent, checker, callContext.returnType);
if (parent.kind === SyntaxKind.CallExpression) {
(usageContext.callContexts || (usageContext.callContexts = [])).push(callContext);
}
else {
(usageContext.constructContexts || (usageContext.constructContexts = [])).push(callContext);
}
}
function inferTypeFromPropertyAccessExpressionContext(parent: PropertyAccessExpression, checker: TypeChecker, usageContext: UsageContext): void {
const name = escapeLeadingUnderscores(parent.name.text);
if (!usageContext.properties) {
usageContext.properties = createUnderscoreEscapedMap<UsageContext>();
}
const propertyUsageContext = {};
inferTypeFromContext(parent, checker, propertyUsageContext);
usageContext.properties.set(name, propertyUsageContext);
}
function inferTypeFromPropertyElementExpressionContext(parent: ElementAccessExpression, node: Expression, checker: TypeChecker, usageContext: UsageContext): void {
if (node === parent.argumentExpression) {
usageContext.isNumberOrString = true;
return;
}
else {
const indexType = checker.getTypeAtLocation(parent);
const indexUsageContext = {};
inferTypeFromContext(parent, checker, indexUsageContext);
if (indexType.flags & TypeFlags.NumberLike) {
usageContext.numberIndexContext = indexUsageContext;
}
else {
usageContext.stringIndexContext = indexUsageContext;
}
}
}
function getTypeFromUsageContext(usageContext: UsageContext, checker: TypeChecker): Type | undefined {
if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) {
return checker.getUnionType([checker.getNumberType(), checker.getStringType()]);
}
else if (usageContext.isNumber) {
return checker.getNumberType();
}
else if (usageContext.isString) {
return checker.getStringType();
}
else if (usageContext.candidateTypes) {
return checker.getWidenedType(checker.getUnionType(map(usageContext.candidateTypes, t => checker.getBaseTypeOfLiteralType(t)), /*subtypeReduction*/ true));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) {
const paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then" as __String).callContexts, /*isRestParameter*/ false, checker);
const types = paramType.getCallSignatures().map(c => c.getReturnType());
return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType());
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push" as __String))) {
return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push" as __String).callContexts, /*isRestParameter*/ false, checker));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) {
const members = createUnderscoreEscapedMap<Symbol>();
const callSignatures: Signature[] = [];
const constructSignatures: Signature[] = [];
let stringIndexInfo: IndexInfo;
let numberIndexInfo: IndexInfo;
if (usageContext.properties) {
usageContext.properties.forEach((context, name) => {
const symbol = checker.createSymbol(SymbolFlags.Property, name);
symbol.type = getTypeFromUsageContext(context, checker);
members.set(name, symbol);
});
}
if (usageContext.callContexts) {
for (const callContext of usageContext.callContexts) {
callSignatures.push(getSignatureFromCallContext(callContext, checker));
}
}
if (usageContext.constructContexts) {
for (const constructContext of usageContext.constructContexts) {
constructSignatures.push(getSignatureFromCallContext(constructContext, checker));
}
}
if (usageContext.numberIndexContext) {
numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false);
}
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false);
}
return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
}
else {
return undefined;
}
}
function getParameterTypeFromCallContexts(parameterIndex: number, callContexts: CallContext[], isRestParameter: boolean, checker: TypeChecker) {
let types: Type[] = [];
if (callContexts) {
for (const callContext of callContexts) {
if (callContext.argumentTypes.length > parameterIndex) {
if (isRestParameter) {
types = concatenate(types, map(callContext.argumentTypes.slice(parameterIndex), a => checker.getBaseTypeOfLiteralType(a)));
}
else {
types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex]));
}
}
}
}
if (types.length) {
const type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true));
return isRestParameter ? checker.createArrayType(type) : type;
}
return undefined;
}
function getSignatureFromCallContext(callContext: CallContext, checker: TypeChecker): Signature {
const parameters: Symbol[] = [];
for (let i = 0; i < callContext.argumentTypes.length; i++) {
const symbol = checker.createSymbol(SymbolFlags.FunctionScopedVariable, escapeLeadingUnderscores(`arg${i}`));
symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i]));
parameters.push(symbol);
}
const returnType = getTypeFromUsageContext(callContext.returnType, checker);
return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
}
function addCandidateType(context: UsageContext, type: Type) {
if (type && !(type.flags & TypeFlags.Any) && !(type.flags & TypeFlags.Never)) {
(context.candidateTypes || (context.candidateTypes = [])).push(type);
}
}
function hasCallContext(usageContext: UsageContext) {
return usageContext && usageContext.callContexts;
}
}
}
+204 -71
View File
@@ -137,7 +137,7 @@ namespace ts.refactor.extractSymbol {
export const FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
export const CannotExtractIdentifier = createMessage("Select more than a single identifier.");
export const CannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
export const CannotCombineWritesAndReturns = createMessage("Cannot combine writes and returns");
export const CannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
export const CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
export const CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
export const CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
@@ -375,7 +375,7 @@ namespace ts.refactor.extractSymbol {
permittedJumps = PermittedJumps.None;
break;
case SyntaxKind.Block:
if (node.parent && node.parent.kind === SyntaxKind.TryStatement && (<TryStatement>node).finallyBlock === node) {
if (node.parent && node.parent.kind === SyntaxKind.TryStatement && (<TryStatement>node.parent).finallyBlock === node) {
// allow unconditional returns from finally blocks
permittedJumps = PermittedJumps.Return;
}
@@ -507,15 +507,16 @@ namespace ts.refactor.extractSymbol {
}
function getFunctionExtractionAtIndex(targetRange: TargetRange, context: RefactorContext, requestedChangesIndex: number): RefactorEditInfo {
const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context);
const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
context.cancellationToken.throwIfCancellationRequested();
return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context);
return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
}
function getConstantExtractionAtIndex(targetRange: TargetRange, context: RefactorContext, requestedChangesIndex: number): RefactorEditInfo {
const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context);
const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
context.cancellationToken.throwIfCancellationRequested();
const expression = isExpression(target)
? target
@@ -674,6 +675,7 @@ namespace ts.refactor.extractSymbol {
node: Statement | Expression | Block,
scope: Scope,
{ usages: usagesInScope, typeParameterUsages, substitutions }: ScopeUsages,
exposedVariableDeclarations: ReadonlyArray<VariableDeclaration>,
range: TargetRange,
context: RefactorContext): RefactorEditInfo {
@@ -731,10 +733,10 @@ namespace ts.refactor.extractSymbol {
// to avoid problems when there are literal types present
if (isExpression(node) && !isJS) {
const contextualType = checker.getContextualType(node);
returnType = checker.typeToTypeNode(contextualType);
returnType = checker.typeToTypeNode(contextualType, scope, NodeBuilderFlags.NoTruncation);
}
const { body, returnValueProperty } = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn));
const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn));
let newFunction: MethodDeclaration | FunctionDeclaration;
if (isClassLike(scope)) {
@@ -796,38 +798,114 @@ namespace ts.refactor.extractSymbol {
call = createAwait(call);
}
if (writes) {
if (exposedVariableDeclarations.length && !writes) {
// No need to mix declarations and writes.
// How could any variables be exposed if there's a return statement?
Debug.assert(!returnValueProperty);
Debug.assert(!(range.facts & RangeFacts.HasReturn));
if (exposedVariableDeclarations.length === 1) {
// Declaring exactly one variable: let x = newFunction();
const variableDeclaration = exposedVariableDeclarations[0];
newNodes.push(createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
[createVariableDeclaration(getSynthesizedDeepClone(variableDeclaration.name), /*type*/ getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns
variableDeclaration.parent.flags)));
}
else {
// Declaring multiple variables / return properties:
// let {x, y} = newFunction();
const bindingElements: BindingElement[] = [];
const typeElements: TypeElement[] = [];
let commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
let sawExplicitType = false;
for (const variableDeclaration of exposedVariableDeclarations) {
bindingElements.push(createBindingElement(
/*dotDotDotToken*/ undefined,
/*propertyName*/ undefined,
/*name*/ getSynthesizedDeepClone(variableDeclaration.name)));
// Being returned through an object literal will have widened the type.
const variableType: TypeNode = checker.typeToTypeNode(
checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)),
scope,
NodeBuilderFlags.NoTruncation);
typeElements.push(createPropertySignature(
/*modifiers*/ undefined,
/*name*/ variableDeclaration.symbol.name,
/*questionToken*/ undefined,
/*type*/ variableType,
/*initializer*/ undefined));
sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined;
commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
}
const typeLiteral: TypeLiteralNode | undefined = sawExplicitType ? createTypeLiteralNode(typeElements) : undefined;
if (typeLiteral) {
setEmitFlags(typeLiteral, EmitFlags.SingleLine);
}
newNodes.push(createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
[createVariableDeclaration(
createObjectBindingPattern(bindingElements),
/*type*/ typeLiteral,
/*initializer*/call)],
commonNodeFlags)));
}
}
else if (exposedVariableDeclarations.length || writes) {
if (exposedVariableDeclarations.length) {
// CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping.
for (const variableDeclaration of exposedVariableDeclarations) {
let flags: NodeFlags = variableDeclaration.parent.flags;
if (flags & NodeFlags.Const) {
flags = (flags & ~NodeFlags.Const) | NodeFlags.Let;
}
newNodes.push(createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
[createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))],
flags)));
}
}
if (returnValueProperty) {
// has both writes and return, need to create variable declaration to hold return value;
newNodes.push(createVariableStatement(
/*modifiers*/ undefined,
[createVariableDeclaration(returnValueProperty, createKeywordTypeNode(SyntaxKind.AnyKeyword))]
));
createVariableDeclarationList(
[createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))],
NodeFlags.Let)));
}
const assignments = getPropertyAssignmentsForWrites(writes);
const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
if (returnValueProperty) {
assignments.unshift(createShorthandPropertyAssignment(returnValueProperty));
}
// propagate writes back
if (assignments.length === 1) {
if (returnValueProperty) {
newNodes.push(createReturn(createIdentifier(returnValueProperty)));
}
else {
newNodes.push(createStatement(createBinary(assignments[0].name, SyntaxKind.EqualsToken, call)));
// We would only have introduced a return value property if there had been
// other assignments to make.
Debug.assert(!returnValueProperty);
if (range.facts & RangeFacts.HasReturn) {
newNodes.push(createReturn());
}
newNodes.push(createStatement(createAssignment(assignments[0].name, call)));
if (range.facts & RangeFacts.HasReturn) {
newNodes.push(createReturn());
}
}
else {
// emit e.g.
// { a, b, __return } = newFunction(a, b);
// return __return;
newNodes.push(createStatement(createBinary(createObjectLiteral(assignments), SyntaxKind.EqualsToken, call)));
newNodes.push(createStatement(createAssignment(createObjectLiteral(assignments), call)));
if (returnValueProperty) {
newNodes.push(createReturn(createIdentifier(returnValueProperty)));
}
@@ -861,6 +939,21 @@ namespace ts.refactor.extractSymbol {
const renameFilename = renameRange.getSourceFile().fileName;
const renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false);
return { renameFilename, renameLocation, edits };
function getTypeDeepCloneUnionUndefined(typeNode: TypeNode | undefined): TypeNode | undefined {
if (typeNode === undefined) {
return undefined;
}
const clone = getSynthesizedDeepClone(typeNode);
let withoutParens = clone;
while (isParenthesizedTypeNode(withoutParens)) {
withoutParens = withoutParens.type;
}
return isUnionTypeNode(withoutParens) && find(withoutParens.types, t => t.kind === SyntaxKind.UndefinedKeyword)
? clone
: createUnionTypeNode([clone, createKeywordTypeNode(SyntaxKind.UndefinedKeyword)]);
}
}
/**
@@ -883,7 +976,7 @@ namespace ts.refactor.extractSymbol {
const variableType = isJS
? undefined
: checker.typeToTypeNode(checker.getContextualType(node));
: checker.typeToTypeNode(checker.getContextualType(node), scope, NodeBuilderFlags.NoTruncation);
const initializer = transformConstantInitializer(node, substitutions);
@@ -1088,21 +1181,22 @@ namespace ts.refactor.extractSymbol {
}
}
function transformFunctionBody(body: Node, writes: ReadonlyArray<UsageEntry>, substitutions: ReadonlyMap<() => Node>, hasReturn: boolean): { body: Block, returnValueProperty: string } {
if (isBlock(body) && !writes && substitutions.size === 0) {
// already block, no writes to propagate back, no substitutions - can use node as is
function transformFunctionBody(body: Node, exposedVariableDeclarations: ReadonlyArray<VariableDeclaration>, writes: ReadonlyArray<UsageEntry>, substitutions: ReadonlyMap<Node>, hasReturn: boolean): { body: Block, returnValueProperty: string } {
const hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0;
if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
// already block, no declarations or writes to propagate back, no substitutions - can use node as is
return { body: createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined };
}
let returnValueProperty: string;
let ignoreReturns = false;
const statements = createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : createReturn(<Expression>body)]);
// rewrite body if either there are writes that should be propagated back via return statements or there are substitutions
if (writes || substitutions.size) {
if (hasWritesOrVariableDeclarations || substitutions.size) {
const rewrittenStatements = visitNodes(statements, visitor).slice();
if (writes && !hasReturn && isStatement(body)) {
if (hasWritesOrVariableDeclarations && !hasReturn && isStatement(body)) {
// add return at the end to propagate writes back in case if control flow falls out of the function body
// it is ok to know that range has at least one return since it we only allow unconditional returns
const assignments = getPropertyAssignmentsForWrites(writes);
const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
if (assignments.length === 1) {
rewrittenStatements.push(createReturn(assignments[0].name));
}
@@ -1117,8 +1211,8 @@ namespace ts.refactor.extractSymbol {
}
function visitor(node: Node): VisitResult<Node> {
if (!ignoreReturns && node.kind === SyntaxKind.ReturnStatement && writes) {
const assignments: ObjectLiteralElementLike[] = getPropertyAssignmentsForWrites(writes);
if (!ignoreReturns && node.kind === SyntaxKind.ReturnStatement && hasWritesOrVariableDeclarations) {
const assignments: ObjectLiteralElementLike[] = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
if ((<ReturnStatement>node).expression) {
if (!returnValueProperty) {
returnValueProperty = "__return";
@@ -1136,21 +1230,21 @@ namespace ts.refactor.extractSymbol {
const oldIgnoreReturns = ignoreReturns;
ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node);
const substitution = substitutions.get(getNodeId(node).toString());
const result = substitution ? substitution() : visitEachChild(node, visitor, nullTransformationContext);
const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext);
ignoreReturns = oldIgnoreReturns;
return result;
}
}
}
function transformConstantInitializer(initializer: Expression, substitutions: ReadonlyMap<() => Node>): Expression {
function transformConstantInitializer(initializer: Expression, substitutions: ReadonlyMap<Node>): Expression {
return substitutions.size
? visitor(initializer) as Expression
: initializer;
function visitor(node: Node): VisitResult<Node> {
const substitution = substitutions.get(getNodeId(node).toString());
return substitution ? substitution() : visitEachChild(node, visitor, nullTransformationContext);
return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext);
}
}
@@ -1240,8 +1334,18 @@ namespace ts.refactor.extractSymbol {
}
}
function getPropertyAssignmentsForWrites(writes: ReadonlyArray<UsageEntry>): ShorthandPropertyAssignment[] {
return writes.map(w => createShorthandPropertyAssignment(w.symbol.name));
function getPropertyAssignmentsForWritesAndVariableDeclarations(
exposedVariableDeclarations: ReadonlyArray<ts.VariableDeclaration>,
writes: ReadonlyArray<UsageEntry>) {
const variableAssignments = map(exposedVariableDeclarations, v => createShorthandPropertyAssignment(v.symbol.name));
const writeAssignments = map(writes, w => createShorthandPropertyAssignment(w.symbol.name));
return variableAssignments === undefined
? writeAssignments
: writeAssignments === undefined
? variableAssignments
: variableAssignments.concat(writeAssignments);
}
function isReadonlyArray(v: any): v is ReadonlyArray<any> {
@@ -1279,7 +1383,7 @@ namespace ts.refactor.extractSymbol {
interface ScopeUsages {
readonly usages: Map<UsageEntry>;
readonly typeParameterUsages: Map<TypeParameter>; // Key is type ID
readonly substitutions: Map<() => Node>;
readonly substitutions: Map<Node>;
}
interface ReadsAndWrites {
@@ -1287,6 +1391,7 @@ namespace ts.refactor.extractSymbol {
readonly usagesPerScope: ReadonlyArray<ScopeUsages>;
readonly functionErrorsPerScope: ReadonlyArray<ReadonlyArray<Diagnostic>>;
readonly constantErrorsPerScope: ReadonlyArray<ReadonlyArray<Diagnostic>>;
readonly exposedVariableDeclarations: ReadonlyArray<VariableDeclaration>;
}
function collectReadsAndWrites(
targetRange: TargetRange,
@@ -1298,10 +1403,13 @@ namespace ts.refactor.extractSymbol {
const allTypeParameterUsages = createMap<TypeParameter>(); // Key is type ID
const usagesPerScope: ScopeUsages[] = [];
const substitutionsPerScope: Map<() => Node>[] = [];
const substitutionsPerScope: Map<Node>[] = [];
const functionErrorsPerScope: Diagnostic[][] = [];
const constantErrorsPerScope: Diagnostic[][] = [];
const visibleDeclarationsInExtractedRange: Symbol[] = [];
const visibleDeclarationsInExtractedRange: NamedDeclaration[] = [];
const exposedVariableSymbolSet = createMap<true>(); // Key is symbol ID
const exposedVariableDeclarations: VariableDeclaration[] = [];
let firstExposedNonVariableDeclaration: NamedDeclaration | undefined = undefined;
const expression = !isReadonlyArray(targetRange.range)
? targetRange.range
@@ -1322,8 +1430,8 @@ namespace ts.refactor.extractSymbol {
// initialize results
for (const scope of scopes) {
usagesPerScope.push({ usages: createMap<UsageEntry>(), typeParameterUsages: createMap<TypeParameter>(), substitutions: createMap<() => Expression>() });
substitutionsPerScope.push(createMap<() => Expression>());
usagesPerScope.push({ usages: createMap<UsageEntry>(), typeParameterUsages: createMap<TypeParameter>(), substitutions: createMap<Expression>() });
substitutionsPerScope.push(createMap<Expression>());
functionErrorsPerScope.push(
isFunctionLikeDeclaration(scope) && scope.kind !== SyntaxKind.FunctionDeclaration
@@ -1346,7 +1454,6 @@ namespace ts.refactor.extractSymbol {
const seenUsages = createMap<Usage>();
const target = isReadonlyArray(targetRange.range) ? createBlock(<Statement[]>targetRange.range) : targetRange.range;
const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]);
const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range;
const inGenericContext = isInGenericContext(unmodifiedNode);
@@ -1392,6 +1499,15 @@ namespace ts.refactor.extractSymbol {
Debug.assert(i === scopes.length);
}
// If there are any declarations in the extracted block that are used in the same enclosing
// lexical scope, we can't move the extraction "up" as those declarations will become unreachable
if (visibleDeclarationsInExtractedRange.length) {
const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent)
? scopes[0]
: getEnclosingBlockScopeContainer(scopes[0]);
forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
for (let i = 0; i < scopes.length; i++) {
const scopeUsages = usagesPerScope[i];
// Special case: in the innermost scope, all usages are available.
@@ -1415,8 +1531,11 @@ namespace ts.refactor.extractSymbol {
}
});
if (hasWrite && !isReadonlyArray(targetRange.range) && isExpression(targetRange.range)) {
const diag = createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns);
// If an expression was extracted, then there shouldn't have been any variable declarations.
Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0);
if (hasWrite && !isReadonlyArray(targetRange.range)) {
const diag = createDiagnosticForNode(targetRange.range, Messages.CannotWriteInExpression);
functionErrorsPerScope[i].push(diag);
constantErrorsPerScope[i].push(diag);
}
@@ -1425,15 +1544,14 @@ namespace ts.refactor.extractSymbol {
functionErrorsPerScope[i].push(diag);
constantErrorsPerScope[i].push(diag);
}
else if (firstExposedNonVariableDeclaration) {
const diag = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.CannotExtractExportedEntity);
functionErrorsPerScope[i].push(diag);
constantErrorsPerScope[i].push(diag);
}
}
// If there are any declarations in the extracted block that are used in the same enclosing
// lexical scope, we can't move the extraction "up" as those declarations will become unreachable
if (visibleDeclarationsInExtractedRange.length) {
forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope };
return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations };
function hasTypeParameters(node: Node) {
return isDeclarationWithTypeParameters(node) &&
@@ -1472,7 +1590,7 @@ namespace ts.refactor.extractSymbol {
}
if (isDeclaration(node) && node.symbol) {
visibleDeclarationsInExtractedRange.push(node.symbol);
visibleDeclarationsInExtractedRange.push(node);
}
if (isAssignmentExpression(node)) {
@@ -1518,11 +1636,7 @@ namespace ts.refactor.extractSymbol {
}
function recordUsagebySymbol(identifier: Identifier, usage: Usage, isTypeName: boolean) {
// If the identifier is both a property name and its value, we're only interested in its value
// (since the name is a declaration and will be included in the extracted range).
const symbol = identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier
? checker.getShorthandAssignmentValueSymbol(identifier.parent)
: checker.getSymbolAtLocation(identifier);
const symbol = getSymbolReferencedByIdentifier(identifier);
if (!symbol) {
// cannot find symbol - do nothing
return undefined;
@@ -1606,36 +1720,55 @@ namespace ts.refactor.extractSymbol {
}
// Otherwise check and recurse.
const sym = checker.getSymbolAtLocation(node);
if (sym && visibleDeclarationsInExtractedRange.some(d => d === sym)) {
const diag = createDiagnosticForNode(node, Messages.CannotExtractExportedEntity);
for (const errors of functionErrorsPerScope) {
errors.push(diag);
const sym = isIdentifier(node)
? getSymbolReferencedByIdentifier(node)
: checker.getSymbolAtLocation(node);
if (sym) {
const decl = find(visibleDeclarationsInExtractedRange, d => d.symbol === sym);
if (decl) {
if (isVariableDeclaration(decl)) {
const idString = decl.symbol.id.toString();
if (!exposedVariableSymbolSet.has(idString)) {
exposedVariableDeclarations.push(decl);
exposedVariableSymbolSet.set(idString, true);
}
}
else {
// CONSIDER: this includes binding elements, which we could
// expose in the same way as variables.
firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
}
}
for (const errors of constantErrorsPerScope) {
errors.push(diag);
}
return true;
}
else {
forEachChild(node, checkForUsedDeclarations);
}
forEachChild(node, checkForUsedDeclarations);
}
function tryReplaceWithQualifiedNameOrPropertyAccess(symbol: Symbol, scopeDecl: Node, isTypeNode: boolean): () => (PropertyAccessExpression | EntityName) {
/**
* Return the symbol referenced by an identifier (even if it declares a different symbol).
*/
function getSymbolReferencedByIdentifier(identifier: Identifier) {
// If the identifier is both a property name and its value, we're only interested in its value
// (since the name is a declaration and will be included in the extracted range).
return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier
? checker.getShorthandAssignmentValueSymbol(identifier.parent)
: checker.getSymbolAtLocation(identifier);
}
function tryReplaceWithQualifiedNameOrPropertyAccess(symbol: Symbol, scopeDecl: Node, isTypeNode: boolean): PropertyAccessExpression | EntityName {
if (!symbol) {
return undefined;
}
if (symbol.getDeclarations().some(d => d.parent === scopeDecl)) {
return () => createIdentifier(symbol.name);
return createIdentifier(symbol.name);
}
const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode);
if (prefix === undefined) {
return undefined;
}
return isTypeNode
? () => createQualifiedName(<EntityName>prefix(), createIdentifier(symbol.name))
: () => createPropertyAccess(<Expression>prefix(), symbol.name);
? createQualifiedName(<EntityName>prefix, createIdentifier(symbol.name))
: createPropertyAccess(<Expression>prefix, symbol.name);
}
}
+35
View File
@@ -1334,4 +1334,39 @@ namespace ts {
}
return position;
}
/**
* Creates a deep, memberwise clone of a node with no source map location.
*
* WARNING: This is an expensive operation and is only intended to be used in refactorings
* and code fixes (because those are triggered by explicit user actions).
*/
export function getSynthesizedDeepClone<T extends Node>(node: T | undefined): T | undefined {
if (node === undefined) {
return undefined;
}
const visited = visitEachChild(node, getSynthesizedDeepClone, nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
const clone = getSynthesizedClone(node);
if (isStringLiteral(clone)) {
clone.textSourceNode = node as any;
}
else if (isNumericLiteral(clone)) {
clone.numericLiteralFlags = (node as any).numericLiteralFlags;
}
clone.pos = node.pos;
clone.end = node.end;
return clone;
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
// would have made.
visited.parent = undefined;
return visited;
}
}
+3
View File
@@ -3068,6 +3068,8 @@ declare namespace ts {
function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node: Node): boolean;
function isSetAccessor(node: Node): node is SetAccessorDeclaration;
function isGetAccessor(node: Node): node is GetAccessorDeclaration;
}
declare namespace ts {
interface ErrorCallback {
@@ -7523,6 +7525,7 @@ declare namespace ts.server {
private createConfiguredProject(configFileName);
private updateNonInferredProjectFiles<T>(project, files, propertyReader);
private updateNonInferredProject<T>(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave);
private sendConfigFileDiagEvent(project, triggerFile);
private getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath);
private getOrCreateSingleInferredProjectIfEnabled();
private createInferredProject(currentDirectory, isSingleInferredProject?, projectRootPath?);
+2
View File
@@ -3123,6 +3123,8 @@ declare namespace ts {
function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node: Node): boolean;
function isSetAccessor(node: Node): node is SetAccessorDeclaration;
function isGetAccessor(node: Node): node is GetAccessorDeclaration;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
@@ -17,7 +17,7 @@ namespace A {
class C {
a() {
let z = 1;
var __return: any;
let __return;
({ __return, z } = this./*RENAME*/newMethod(z));
return __return;
}
@@ -36,7 +36,7 @@ namespace A {
class C {
a() {
let z = 1;
var __return: any;
let __return;
({ __return, z } = /*RENAME*/newFunction(z));
return __return;
}
@@ -55,7 +55,7 @@ namespace A {
class C {
a() {
let z = 1;
var __return: any;
let __return;
({ __return, y, z } = /*RENAME*/newFunction(y, z));
return __return;
}
@@ -20,7 +20,7 @@ namespace A {
b() {}
a() {
let z = 1;
var __return: any;
let __return;
({ __return, z } = this./*RENAME*/newMethod(z));
return __return;
}
@@ -43,7 +43,7 @@ namespace A {
function a() {
let a = 1;
var __return: any;
let __return;
({ __return, a } = /*RENAME*/newFunction(a));
return __return;
}
@@ -65,7 +65,7 @@ namespace A {
function a() {
let a = 1;
var __return: any;
let __return;
({ __return, a } = /*RENAME*/newFunction(a));
return __return;
}
@@ -87,7 +87,7 @@ namespace A {
function a() {
let a = 1;
var __return: any;
let __return;
({ __return, a } = /*RENAME*/newFunction(x, a));
return __return;
}
@@ -49,7 +49,7 @@ namespace A {
function a() {
let a = 1;
var __return: any;
let __return;
({ __return, a } = /*RENAME*/newFunction(a));
return __return;
}
@@ -73,7 +73,7 @@ namespace A {
function a() {
let a = 1;
var __return: any;
let __return;
({ __return, a } = /*RENAME*/newFunction(a));
return __return;
}
@@ -97,7 +97,7 @@ namespace A {
function a() {
let a = 1;
var __return: any;
let __return;
({ __return, a } = /*RENAME*/newFunction(x, a));
return __return;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/const x = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
const x = /*RENAME*/newFunction();
x;
function newFunction() {
const x = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/const x = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
const x = /*RENAME*/newFunction();
x;
function newFunction() {
const x = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/const x: number = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
const x: number = /*RENAME*/newFunction();
x;
function newFunction() {
const x: number = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/const x: number = 1;/*|]*/
x; x;
// ==SCOPE::Extract to function in global scope==
const x: number = /*RENAME*/newFunction();
x; x;
function newFunction() {
const x: number = 1;
return x;
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
/*[#|*/var x = 1;
var x = 2;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
var x = /*RENAME*/newFunction();
x;
function newFunction() {
var x = 1;
var x = 2;
return x;
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
/*[#|*/var x = 1;
var x = 2;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
var x = /*RENAME*/newFunction();
x;
function newFunction() {
var x = 1;
var x = 2;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/let x = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
let x = /*RENAME*/newFunction();
x;
function newFunction() {
let x = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/let x = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
let x = /*RENAME*/newFunction();
x;
function newFunction() {
let x = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/let x: number = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
let x: number = /*RENAME*/newFunction();
x;
function newFunction() {
let x: number = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/const x = 1, y: string = "a";/*|]*/
x; y;
// ==SCOPE::Extract to function in global scope==
const { x, y }: { x: number; y: string; } = /*RENAME*/newFunction();
x; y;
function newFunction() {
const x = 1, y: string = "a";
return { x, y };
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
/*[#|*/const x = 1, y = "a";
const z = 3;/*|]*/
x; y; z;
// ==SCOPE::Extract to function in global scope==
const { x, y, z } = /*RENAME*/newFunction();
x; y; z;
function newFunction() {
const x = 1, y = "a";
const z = 3;
return { x, y, z };
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
/*[#|*/const x = 1, y = "a";
const z = 3;/*|]*/
x; y; z;
// ==SCOPE::Extract to function in global scope==
const { x, y, z } = /*RENAME*/newFunction();
x; y; z;
function newFunction() {
const x = 1, y = "a";
const z = 3;
return { x, y, z };
}
@@ -0,0 +1,16 @@
// ==ORIGINAL==
/*[#|*/const x = 1, y: string = "a";
let z = 3;/*|]*/
x; y; z;
// ==SCOPE::Extract to function in global scope==
var { x, y, z }: { x: number; y: string; z: number; } = /*RENAME*/newFunction();
x; y; z;
function newFunction() {
const x = 1, y: string = "a";
let z = 3;
return { x, y, z };
}
@@ -0,0 +1,27 @@
// ==ORIGINAL==
function f() {
/*[#|*/let x;/*|]*/
return { x };
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let x = /*RENAME*/newFunction();
return { x };
function newFunction() {
let x;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let x = /*RENAME*/newFunction();
return { x };
}
function newFunction() {
let x;
return x;
}
@@ -0,0 +1,27 @@
// ==ORIGINAL==
function f() {
/*[#|*/let x;/*|]*/
return { x };
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let x = /*RENAME*/newFunction();
return { x };
function newFunction() {
let x;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let x = /*RENAME*/newFunction();
return { x };
}
function newFunction() {
let x;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/var x = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
var x = /*RENAME*/newFunction();
x;
function newFunction() {
var x = 1;
return x;
}
@@ -0,0 +1,14 @@
// ==ORIGINAL==
/*[#|*/var x = 1;/*|]*/
x;
// ==SCOPE::Extract to function in global scope==
var x = /*RENAME*/newFunction();
x;
function newFunction() {
var x = 1;
return x;
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/const x = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
const x = /*RENAME*/newFunction();
a; x;
function newFunction() {
const x = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a) {
const x = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/const x = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
const x = /*RENAME*/newFunction();
a; x;
function newFunction() {
const x = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
const x = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/const x: number = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
const x: number = /*RENAME*/newFunction();
a; x;
function newFunction() {
const x: number = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: number | undefined;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
const x: number = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x: 0o10 | 10 | 0b10 = 10;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let x: 8 | 10 | 2 = /*RENAME*/newFunction();
a; x;
function newFunction() {
let x: 0o10 | 10 | 0b10 = 10;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: (8 | 10 | 2) | undefined;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
let x: 0o10 | 10 | 0b10 = 10;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x: "a" | 'b' = 'a';
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let x: "a" | 'b' = /*RENAME*/newFunction();
a; x;
function newFunction() {
let x: "a" | 'b' = 'a';
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: ("a" | 'b') | undefined;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
let x: "a" | 'b' = 'a';
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let x = /*RENAME*/newFunction();
a; x;
function newFunction() {
let x = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a) {
let x = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let x = /*RENAME*/newFunction();
a; x;
function newFunction() {
let x = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
let x = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x: number = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let x: number = /*RENAME*/newFunction();
a; x;
function newFunction() {
let x: number = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: number | undefined;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
let x: number = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = 'a';
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = /*RENAME*/newFunction();
a; x;
function newFunction() {
let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = 'a';
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: (/*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/) | undefined;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = 'a';
a++;
return { x, a };
}
@@ -0,0 +1,38 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/const x = 1;
let y = 2;
a++;/*|]*/
a; x; y;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
var { x, y } = /*RENAME*/newFunction();
a; x; y;
function newFunction() {
const x = 1;
let y = 2;
a++;
return { x, y };
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x;
let y;
({ x, y, a } = /*RENAME*/newFunction(a));
a; x; y;
}
function newFunction(a) {
const x = 1;
let y = 2;
a++;
return { x, y, a };
}
@@ -0,0 +1,38 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/const x = 1;
let y = 2;
a++;/*|]*/
a; x; y;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
var { x, y } = /*RENAME*/newFunction();
a; x; y;
function newFunction() {
const x = 1;
let y = 2;
a++;
return { x, y };
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x;
let y;
({ x, y, a } = /*RENAME*/newFunction(a));
a; x; y;
}
function newFunction(a: number) {
const x = 1;
let y = 2;
a++;
return { x, y, a };
}
@@ -0,0 +1,38 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/var x = 1;
let y = 2;
a++;/*|]*/
a; x; y;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
var { x, y } = /*RENAME*/newFunction();
a; x; y;
function newFunction() {
var x = 1;
let y = 2;
a++;
return { x, y };
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
var x;
let y;
({ x, y, a } = /*RENAME*/newFunction(a));
a; x; y;
}
function newFunction(a) {
var x = 1;
let y = 2;
a++;
return { x, y, a };
}
@@ -0,0 +1,38 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/var x = 1;
let y = 2;
a++;/*|]*/
a; x; y;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
var { x, y } = /*RENAME*/newFunction();
a; x; y;
function newFunction() {
var x = 1;
let y = 2;
a++;
return { x, y };
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
var x;
let y;
({ x, y, a } = /*RENAME*/newFunction(a));
a; x; y;
}
function newFunction(a: number) {
var x = 1;
let y = 2;
a++;
return { x, y, a };
}
@@ -0,0 +1,38 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x: number = 1;
let y = 2;
a++;/*|]*/
a; x; y;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let { x, y }: { x: number; y: number; } = /*RENAME*/newFunction();
a; x; y;
function newFunction() {
let x: number = 1;
let y = 2;
a++;
return { x, y };
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: number | undefined;
let y;
({ x, y, a } = /*RENAME*/newFunction(a));
a; x; y;
}
function newFunction(a: number) {
let x: number = 1;
let y = 2;
a++;
return { x, y, a };
}
@@ -0,0 +1,42 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/let x: number | undefined = 1;
let y: undefined | number = 2;
let z: (undefined | number) = 3;
a++;/*|]*/
a; x; y; z;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
let { x, y, z }: { x: number; y: number; z: number; } = /*RENAME*/newFunction();
a; x; y; z;
function newFunction() {
let x: number | undefined = 1;
let y: undefined | number = 2;
let z: (undefined | number) = 3;
a++;
return { x, y, z };
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
let x: number | undefined;
let y: undefined | number;
let z: (undefined | number);
({ x, y, z, a } = /*RENAME*/newFunction(a));
a; x; y; z;
}
function newFunction(a: number) {
let x: number | undefined = 1;
let y: undefined | number = 2;
let z: (undefined | number) = 3;
a++;
return { x, y, z, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/var x = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
var x = /*RENAME*/newFunction();
a; x;
function newFunction() {
var x = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
var x;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a) {
var x = 1;
a++;
return { x, a };
}
@@ -0,0 +1,34 @@
// ==ORIGINAL==
function f() {
let a = 1;
/*[#|*/var x = 1;
a++;/*|]*/
a; x;
}
// ==SCOPE::Extract to inner function in function 'f'==
function f() {
let a = 1;
var x = /*RENAME*/newFunction();
a; x;
function newFunction() {
var x = 1;
a++;
return x;
}
}
// ==SCOPE::Extract to function in global scope==
function f() {
let a = 1;
var x;
({ x, a } = /*RENAME*/newFunction(a));
a; x;
}
function newFunction(a: number) {
var x = 1;
a++;
return { x, a };
}
@@ -0,0 +1,49 @@
//// [indirectTypeParameterReferences.ts]
// Repro from #19043
type B = {b: string}
const flowtypes = <A>(b: B) => {
type Combined = A & B
const combined = (fn: (combined: Combined) => void) => null
const literal = (fn: (aPlusB: A & B) => void) => null
return {combined, literal}
}
const {combined, literal} = flowtypes<{a: string}>({b: 'b-value'})
literal(aPlusB => {
aPlusB.b
aPlusB.a
})
combined(comb => {
comb.b
comb.a
})
// Repro from #19091
declare function f<T>(a: T): { a: typeof a };
let n: number = f(2).a;
//// [indirectTypeParameterReferences.js]
// Repro from #19043
var flowtypes = function (b) {
var combined = function (fn) { return null; };
var literal = function (fn) { return null; };
return { combined: combined, literal: literal };
};
var _a = flowtypes({ b: 'b-value' }), combined = _a.combined, literal = _a.literal;
literal(function (aPlusB) {
aPlusB.b;
aPlusB.a;
});
combined(function (comb) {
comb.b;
comb.a;
});
var n = f(2).a;
@@ -0,0 +1,91 @@
=== tests/cases/compiler/indirectTypeParameterReferences.ts ===
// Repro from #19043
type B = {b: string}
>B : Symbol(B, Decl(indirectTypeParameterReferences.ts, 0, 0))
>b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 2, 10))
const flowtypes = <A>(b: B) => {
>flowtypes : Symbol(flowtypes, Decl(indirectTypeParameterReferences.ts, 4, 5))
>A : Symbol(A, Decl(indirectTypeParameterReferences.ts, 4, 19))
>b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 4, 22))
>B : Symbol(B, Decl(indirectTypeParameterReferences.ts, 0, 0))
type Combined = A & B
>Combined : Symbol(Combined, Decl(indirectTypeParameterReferences.ts, 4, 32))
>A : Symbol(A, Decl(indirectTypeParameterReferences.ts, 4, 19))
>B : Symbol(B, Decl(indirectTypeParameterReferences.ts, 0, 0))
const combined = (fn: (combined: Combined) => void) => null
>combined : Symbol(combined, Decl(indirectTypeParameterReferences.ts, 7, 7))
>fn : Symbol(fn, Decl(indirectTypeParameterReferences.ts, 7, 20))
>combined : Symbol(combined, Decl(indirectTypeParameterReferences.ts, 7, 25))
>Combined : Symbol(Combined, Decl(indirectTypeParameterReferences.ts, 4, 32))
const literal = (fn: (aPlusB: A & B) => void) => null
>literal : Symbol(literal, Decl(indirectTypeParameterReferences.ts, 8, 7))
>fn : Symbol(fn, Decl(indirectTypeParameterReferences.ts, 8, 19))
>aPlusB : Symbol(aPlusB, Decl(indirectTypeParameterReferences.ts, 8, 24))
>A : Symbol(A, Decl(indirectTypeParameterReferences.ts, 4, 19))
>B : Symbol(B, Decl(indirectTypeParameterReferences.ts, 0, 0))
return {combined, literal}
>combined : Symbol(combined, Decl(indirectTypeParameterReferences.ts, 10, 10))
>literal : Symbol(literal, Decl(indirectTypeParameterReferences.ts, 10, 19))
}
const {combined, literal} = flowtypes<{a: string}>({b: 'b-value'})
>combined : Symbol(combined, Decl(indirectTypeParameterReferences.ts, 13, 7))
>literal : Symbol(literal, Decl(indirectTypeParameterReferences.ts, 13, 16))
>flowtypes : Symbol(flowtypes, Decl(indirectTypeParameterReferences.ts, 4, 5))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 13, 39))
>b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 13, 52))
literal(aPlusB => {
>literal : Symbol(literal, Decl(indirectTypeParameterReferences.ts, 13, 16))
>aPlusB : Symbol(aPlusB, Decl(indirectTypeParameterReferences.ts, 15, 8))
aPlusB.b
>aPlusB.b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 2, 10))
>aPlusB : Symbol(aPlusB, Decl(indirectTypeParameterReferences.ts, 15, 8))
>b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 2, 10))
aPlusB.a
>aPlusB.a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 13, 39))
>aPlusB : Symbol(aPlusB, Decl(indirectTypeParameterReferences.ts, 15, 8))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 13, 39))
})
combined(comb => {
>combined : Symbol(combined, Decl(indirectTypeParameterReferences.ts, 13, 7))
>comb : Symbol(comb, Decl(indirectTypeParameterReferences.ts, 20, 9))
comb.b
>comb.b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 2, 10))
>comb : Symbol(comb, Decl(indirectTypeParameterReferences.ts, 20, 9))
>b : Symbol(b, Decl(indirectTypeParameterReferences.ts, 2, 10))
comb.a
>comb.a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 13, 39))
>comb : Symbol(comb, Decl(indirectTypeParameterReferences.ts, 20, 9))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 13, 39))
})
// Repro from #19091
declare function f<T>(a: T): { a: typeof a };
>f : Symbol(f, Decl(indirectTypeParameterReferences.ts, 23, 2))
>T : Symbol(T, Decl(indirectTypeParameterReferences.ts, 27, 19))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 27, 22))
>T : Symbol(T, Decl(indirectTypeParameterReferences.ts, 27, 19))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 27, 30))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 27, 22))
let n: number = f(2).a;
>n : Symbol(n, Decl(indirectTypeParameterReferences.ts, 28, 3))
>f(2).a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 27, 30))
>f : Symbol(f, Decl(indirectTypeParameterReferences.ts, 23, 2))
>a : Symbol(a, Decl(indirectTypeParameterReferences.ts, 27, 30))
@@ -0,0 +1,106 @@
=== tests/cases/compiler/indirectTypeParameterReferences.ts ===
// Repro from #19043
type B = {b: string}
>B : B
>b : string
const flowtypes = <A>(b: B) => {
>flowtypes : <A>(b: B) => { combined: (fn: (combined: A & B) => void) => any; literal: (fn: (aPlusB: A & B) => void) => any; }
><A>(b: B) => { type Combined = A & B const combined = (fn: (combined: Combined) => void) => null const literal = (fn: (aPlusB: A & B) => void) => null return {combined, literal}} : <A>(b: B) => { combined: (fn: (combined: A & B) => void) => any; literal: (fn: (aPlusB: A & B) => void) => any; }
>A : A
>b : B
>B : B
type Combined = A & B
>Combined : A & B
>A : A
>B : B
const combined = (fn: (combined: Combined) => void) => null
>combined : (fn: (combined: A & B) => void) => any
>(fn: (combined: Combined) => void) => null : (fn: (combined: A & B) => void) => any
>fn : (combined: A & B) => void
>combined : A & B
>Combined : A & B
>null : null
const literal = (fn: (aPlusB: A & B) => void) => null
>literal : (fn: (aPlusB: A & B) => void) => any
>(fn: (aPlusB: A & B) => void) => null : (fn: (aPlusB: A & B) => void) => any
>fn : (aPlusB: A & B) => void
>aPlusB : A & B
>A : A
>B : B
>null : null
return {combined, literal}
>{combined, literal} : { combined: (fn: (combined: A & B) => void) => any; literal: (fn: (aPlusB: A & B) => void) => any; }
>combined : (fn: (combined: A & B) => void) => any
>literal : (fn: (aPlusB: A & B) => void) => any
}
const {combined, literal} = flowtypes<{a: string}>({b: 'b-value'})
>combined : (fn: (combined: { a: string; } & B) => void) => any
>literal : (fn: (aPlusB: { a: string; } & B) => void) => any
>flowtypes<{a: string}>({b: 'b-value'}) : { combined: (fn: (combined: { a: string; } & B) => void) => any; literal: (fn: (aPlusB: { a: string; } & B) => void) => any; }
>flowtypes : <A>(b: B) => { combined: (fn: (combined: A & B) => void) => any; literal: (fn: (aPlusB: A & B) => void) => any; }
>a : string
>{b: 'b-value'} : { b: string; }
>b : string
>'b-value' : "b-value"
literal(aPlusB => {
>literal(aPlusB => { aPlusB.b aPlusB.a}) : any
>literal : (fn: (aPlusB: { a: string; } & B) => void) => any
>aPlusB => { aPlusB.b aPlusB.a} : (aPlusB: { a: string; } & B) => void
>aPlusB : { a: string; } & B
aPlusB.b
>aPlusB.b : string
>aPlusB : { a: string; } & B
>b : string
aPlusB.a
>aPlusB.a : string
>aPlusB : { a: string; } & B
>a : string
})
combined(comb => {
>combined(comb => { comb.b comb.a}) : any
>combined : (fn: (combined: { a: string; } & B) => void) => any
>comb => { comb.b comb.a} : (comb: { a: string; } & B) => void
>comb : { a: string; } & B
comb.b
>comb.b : string
>comb : { a: string; } & B
>b : string
comb.a
>comb.a : string
>comb : { a: string; } & B
>a : string
})
// Repro from #19091
declare function f<T>(a: T): { a: typeof a };
>f : <T>(a: T) => { a: T; }
>T : T
>a : T
>T : T
>a : T
>a : T
let n: number = f(2).a;
>n : number
>f(2).a : number
>f(2) : { a: number; }
>f : <T>(a: T) => { a: T; }
>2 : 2
>a : number
@@ -0,0 +1,28 @@
//// [tests/cases/compiler/inferredIndexerOnNamespaceImport.ts] ////
//// [foo.ts]
export const x = 3;
export const y = 5;
//// [bar.ts]
import * as foo from "./foo";
function f(map: { [k: string]: number }) {
// ...
}
f(foo);
//// [foo.js]
"use strict";
exports.__esModule = true;
exports.x = 3;
exports.y = 5;
//// [bar.js]
"use strict";
exports.__esModule = true;
var foo = require("./foo");
function f(map) {
// ...
}
f(foo);
@@ -0,0 +1,23 @@
=== tests/cases/compiler/foo.ts ===
export const x = 3;
>x : Symbol(x, Decl(foo.ts, 0, 12))
export const y = 5;
>y : Symbol(y, Decl(foo.ts, 1, 12))
=== tests/cases/compiler/bar.ts ===
import * as foo from "./foo";
>foo : Symbol(foo, Decl(bar.ts, 0, 6))
function f(map: { [k: string]: number }) {
>f : Symbol(f, Decl(bar.ts, 0, 29))
>map : Symbol(map, Decl(bar.ts, 2, 11))
>k : Symbol(k, Decl(bar.ts, 2, 19))
// ...
}
f(foo);
>f : Symbol(f, Decl(bar.ts, 0, 29))
>foo : Symbol(foo, Decl(bar.ts, 0, 6))
@@ -0,0 +1,26 @@
=== tests/cases/compiler/foo.ts ===
export const x = 3;
>x : 3
>3 : 3
export const y = 5;
>y : 5
>5 : 5
=== tests/cases/compiler/bar.ts ===
import * as foo from "./foo";
>foo : typeof foo
function f(map: { [k: string]: number }) {
>f : (map: { [k: string]: number; }) => void
>map : { [k: string]: number; }
>k : string
// ...
}
f(foo);
>f(foo) : void
>f : (map: { [k: string]: number; }) => void
>foo : typeof foo
@@ -0,0 +1,24 @@
tests/cases/compiler/mutuallyRecursiveCallbacks.ts(7,1): error TS2322: Type '<T>(bar: Bar<T>) => void' is not assignable to type 'Bar<{}>'.
Types of parameters 'bar' and 'foo' are incompatible.
Types of parameters 'bar' and 'foo' are incompatible.
Type 'Foo<{}>' is not assignable to type 'Bar<{}>'.
Types of parameters 'bar' and 'foo' are incompatible.
Type 'void' is not assignable to type 'Foo<{}>'.
==== tests/cases/compiler/mutuallyRecursiveCallbacks.ts (1 errors) ====
// Repro from #18277
interface Foo<T> { (bar: Bar<T>): void };
type Bar<T> = (foo: Foo<T>) => Foo<T>;
declare function foo<T>(bar: Bar<T>): void;
declare var bar: Bar<{}>;
bar = foo;
~~~
!!! error TS2322: Type '<T>(bar: Bar<T>) => void' is not assignable to type 'Bar<{}>'.
!!! error TS2322: Types of parameters 'bar' and 'foo' are incompatible.
!!! error TS2322: Types of parameters 'bar' and 'foo' are incompatible.
!!! error TS2322: Type 'Foo<{}>' is not assignable to type 'Bar<{}>'.
!!! error TS2322: Types of parameters 'bar' and 'foo' are incompatible.
!!! error TS2322: Type 'void' is not assignable to type 'Foo<{}>'.
@@ -0,0 +1,14 @@
//// [mutuallyRecursiveCallbacks.ts]
// Repro from #18277
interface Foo<T> { (bar: Bar<T>): void };
type Bar<T> = (foo: Foo<T>) => Foo<T>;
declare function foo<T>(bar: Bar<T>): void;
declare var bar: Bar<{}>;
bar = foo;
//// [mutuallyRecursiveCallbacks.js]
// Repro from #18277
;
bar = foo;
@@ -0,0 +1,34 @@
=== tests/cases/compiler/mutuallyRecursiveCallbacks.ts ===
// Repro from #18277
interface Foo<T> { (bar: Bar<T>): void };
>Foo : Symbol(Foo, Decl(mutuallyRecursiveCallbacks.ts, 0, 0))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 2, 14))
>bar : Symbol(bar, Decl(mutuallyRecursiveCallbacks.ts, 2, 20))
>Bar : Symbol(Bar, Decl(mutuallyRecursiveCallbacks.ts, 2, 41))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 2, 14))
type Bar<T> = (foo: Foo<T>) => Foo<T>;
>Bar : Symbol(Bar, Decl(mutuallyRecursiveCallbacks.ts, 2, 41))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 3, 9))
>foo : Symbol(foo, Decl(mutuallyRecursiveCallbacks.ts, 3, 15))
>Foo : Symbol(Foo, Decl(mutuallyRecursiveCallbacks.ts, 0, 0))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 3, 9))
>Foo : Symbol(Foo, Decl(mutuallyRecursiveCallbacks.ts, 0, 0))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 3, 9))
declare function foo<T>(bar: Bar<T>): void;
>foo : Symbol(foo, Decl(mutuallyRecursiveCallbacks.ts, 3, 38))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 4, 21))
>bar : Symbol(bar, Decl(mutuallyRecursiveCallbacks.ts, 4, 24))
>Bar : Symbol(Bar, Decl(mutuallyRecursiveCallbacks.ts, 2, 41))
>T : Symbol(T, Decl(mutuallyRecursiveCallbacks.ts, 4, 21))
declare var bar: Bar<{}>;
>bar : Symbol(bar, Decl(mutuallyRecursiveCallbacks.ts, 5, 11))
>Bar : Symbol(Bar, Decl(mutuallyRecursiveCallbacks.ts, 2, 41))
bar = foo;
>bar : Symbol(bar, Decl(mutuallyRecursiveCallbacks.ts, 5, 11))
>foo : Symbol(foo, Decl(mutuallyRecursiveCallbacks.ts, 3, 38))
@@ -0,0 +1,35 @@
=== tests/cases/compiler/mutuallyRecursiveCallbacks.ts ===
// Repro from #18277
interface Foo<T> { (bar: Bar<T>): void };
>Foo : Foo<T>
>T : T
>bar : Bar<T>
>Bar : Bar<T>
>T : T
type Bar<T> = (foo: Foo<T>) => Foo<T>;
>Bar : Bar<T>
>T : T
>foo : Foo<T>
>Foo : Foo<T>
>T : T
>Foo : Foo<T>
>T : T
declare function foo<T>(bar: Bar<T>): void;
>foo : <T>(bar: Bar<T>) => void
>T : T
>bar : Bar<T>
>Bar : Bar<T>
>T : T
declare var bar: Bar<{}>;
>bar : Bar<{}>
>Bar : Bar<T>
bar = foo;
>bar = foo : <T>(bar: Bar<T>) => void
>bar : Bar<{}>
>foo : <T>(bar: Bar<T>) => void
@@ -0,0 +1,29 @@
// Repro from #19043
type B = {b: string}
const flowtypes = <A>(b: B) => {
type Combined = A & B
const combined = (fn: (combined: Combined) => void) => null
const literal = (fn: (aPlusB: A & B) => void) => null
return {combined, literal}
}
const {combined, literal} = flowtypes<{a: string}>({b: 'b-value'})
literal(aPlusB => {
aPlusB.b
aPlusB.a
})
combined(comb => {
comb.b
comb.a
})
// Repro from #19091
declare function f<T>(a: T): { a: typeof a };
let n: number = f(2).a;
@@ -0,0 +1,12 @@
// @filename: foo.ts
export const x = 3;
export const y = 5;
// @filename: bar.ts
import * as foo from "./foo";
function f(map: { [k: string]: number }) {
// ...
}
f(foo);
@@ -0,0 +1,7 @@
// Repro from #18277
interface Foo<T> { (bar: Bar<T>): void };
type Bar<T> = (foo: Foo<T>) => Foo<T>;
declare function foo<T>(bar: Bar<T>): void;
declare var bar: Bar<{}>;
bar = foo;
@@ -0,0 +1,9 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////[|var foo;|]
////function f() {
//// foo += 2;
////}
verify.rangeAfterCodeFix("var foo: number;",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0);
@@ -0,0 +1,10 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////declare class C {
//// [|get x();|]
////}
////}
////(new C).x = 1;
verify.rangeAfterCodeFix("get x(): number;", undefined, undefined, 0);
@@ -0,0 +1,11 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////class C {
//// [|get x() |]{
//// return undefined;
//// }
////}
////(new C).x = 1;
verify.rangeAfterCodeFix("get x(): number", undefined, undefined, 0);
@@ -0,0 +1,20 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////function f1([|a |]) { }
////function h1() {
//// class C { p: number };
//// f1({ ofTypeC: new C() });
////}
////
////function f2([|a |]) { }
////function h2() {
//// interface I { a: number }
//// var i: I = {a : 1};
//// f2(i);
//// f2(2);
//// f2(false);
////}
////
verify.not.codeFixAvailable();
@@ -0,0 +1,11 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////class C {
//// [|p;|]
//// method() {
//// this.p.push(10);
//// }
////}
verify.rangeAfterCodeFix("p: number[];");
@@ -0,0 +1,10 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////interface I {
//// [|p;|]
////}
////var i: I;
////i.p = 0;
verify.rangeAfterCodeFix("p: number;");
@@ -0,0 +1,9 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////class C {
//// constructor([|public p)|] { }
////}
////new C("string");
verify.rangeAfterCodeFix("public p: string)");
@@ -0,0 +1,9 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
//// function f([|a, b, c, d: number, e = 0, ...d |]) {
//// }
//// f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string");
verify.rangeAfterCodeFix("a: number, b: string, c: { a: number; }, d: number, e = 0, ...d: (string | number)[]", /*includeWhiteSpace*/ false, /*errorCode*/ undefined, /*index*/ 1);
@@ -0,0 +1,9 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////function f([|a? |]){
////}
////f();
////f(1);
verify.rangeAfterCodeFix("a?: number");
@@ -0,0 +1,8 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////function f([|a? |]){
//// if (a < 9) return;
////}
verify.rangeAfterCodeFix("a?: number");
@@ -0,0 +1,11 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////function f(a: number, [|...rest |]){
////}
////f(1);
////f(2, "s1");
////f(3, "s1", "s2");
////f(3, "s1", "s2", "s3", "s4");
verify.rangeAfterCodeFix("...rest: string[]");
@@ -0,0 +1,11 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////function f(a: number, [|...rest |]){
////}
////f(1);
////f(2, "s1");
////f(3, false, "s2");
////f(4, "s1", "s2", false, "s4");
verify.rangeAfterCodeFix("...rest: (string | boolean)[]");
@@ -0,0 +1,8 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////function f(a: number, [|...rest |]){
//// rest.push(22);
////}
verify.rangeAfterCodeFix("...rest: number[]");
@@ -0,0 +1,10 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////class C {
//// set [|x(v)|] {
//// }
////}
////(new C).x = 1;
verify.rangeAfterCodeFix("x(v: number)", undefined, undefined, 0);
@@ -0,0 +1,10 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////class C {
//// set [|x(v)|] {
//// }
////}
////(new C).x = 1;
verify.rangeAfterCodeFix("x(v: number)", undefined, undefined, 1);
@@ -0,0 +1,9 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////[|var x;|]
////function f() {
//// x++;
////}
verify.rangeAfterCodeFix("var x: number;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0);
@@ -0,0 +1,13 @@
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
////[|var x;
////function f() {
//// x++;
////}|]
verify.rangeAfterCodeFix(`var x: number;
function f() {
x++;
}
`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 1);
+1 -1
View File
@@ -18,7 +18,7 @@ edit.applyRefactor({
newContent:
`function foo() {
var i = 10;
var __return: any;
let __return;
({ __return, i } = /*RENAME*/newFunction(i));
return __return;
}