From d17e662bca3701f3be6e0d5c461894ad3511eaa9 Mon Sep 17 00:00:00 2001 From: Yuya Tanaka Date: Mon, 13 May 2019 16:45:56 +0900 Subject: [PATCH 001/151] Fix outdated comments for unknown type --- src/compiler/checker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 64834befee1..42e5dc91e63 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7474,7 +7474,7 @@ namespace ts { else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', - // the modifiers type is T. Otherwise, the modifiers type is {}. + // the modifiers type is T. Otherwise, the modifiers type is unknown. const declaredType = getTypeFromMappedTypeNode(type.declaration); const constraint = getConstraintTypeFromMappedType(declaredType); const extendedConstraint = constraint && constraint.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(constraint) : constraint; @@ -22570,7 +22570,7 @@ namespace ts { links.type = contextualType; const decl = parameter.valueDeclaration as ParameterDeclaration; if (decl.name.kind !== SyntaxKind.Identifier) { - // if inference didn't come up with anything but {}, fall back to the binding pattern if present. + // if inference didn't come up with anything but unknown, fall back to the binding pattern if present. if (links.type === unknownType) { links.type = getTypeFromBindingPattern(decl.name); } From f1a0a7f863a0b247471626a0188c42c59ddbe18e Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Mon, 17 Jun 2019 13:30:07 -0700 Subject: [PATCH 002/151] Don't let the additional property setting on an object show up as a definition for the lanmguage server --- src/services/goToDefinition.ts | 12 ++++++++---- .../goToDefinitionPropertyAssignment.ts | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 tests/cases/fourslash/goToDefinitionPropertyAssignment.ts diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 8f495aadfe1..19959871500 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -26,7 +26,7 @@ namespace ts.GoToDefinition { if (!symbol) { return getDefinitionInfoForIndexSignatures(node, typeChecker); } - + const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { @@ -233,20 +233,24 @@ namespace ts.GoToDefinition { } function getDefinitionFromSymbol(typeChecker: TypeChecker, symbol: Symbol, node: Node): DefinitionInfo[] | undefined { - return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(symbol.declarations, declaration => createDefinitionInfo(declaration, typeChecker, symbol, node)); + // There are cases when you extend a function by adding properties to it afterwards, + // we want to strip those extra properties + const filteredDeclarations = symbol.declarations.filter(d => !ts.isAssignmentDeclaration(d) || d === symbol.valueDeclaration) + + return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(filteredDeclarations, declaration => createDefinitionInfo(declaration, typeChecker, symbol, node)); function getConstructSignatureDefinition(): DefinitionInfo[] | undefined { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class if (symbol.flags & SymbolFlags.Class && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) { - const cls = find(symbol.declarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); + const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } } function getCallSignatureDefinition(): DefinitionInfo[] | undefined { return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) - ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ false) : undefined; } diff --git a/tests/cases/fourslash/goToDefinitionPropertyAssignment.ts b/tests/cases/fourslash/goToDefinitionPropertyAssignment.ts new file mode 100644 index 00000000000..5da8604f548 --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionPropertyAssignment.ts @@ -0,0 +1,16 @@ +/// + +//// export const /*FunctionResult*/Component = () => { return "OK"} +//// Component./*PropertyResult*/displayName = 'Component' +//// +//// [|/*FunctionClick*/Component|] +//// +//// Component.[|/*PropertyClick*/displayName|] + +verify.goToDefinition("FunctionClick", "FunctionResult") + +verify.goToDefinition("PropertyClick", "PropertyResult") + +// export const Component = () => { return "OK"} +// Component.displayName = 'Component' + From 6b33dda121e98b9b64e5d04f5f5828c4cddb5168 Mon Sep 17 00:00:00 2001 From: sisisin Date: Wed, 19 Jun 2019 19:08:01 +0900 Subject: [PATCH 003/151] chore(tsserver): fix typo --- src/services/importTracker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 2734d059000..7724292d444 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -434,7 +434,7 @@ namespace ts.FindAllReferences { /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. * If at an import, look locally for the symbol it imports. - * If an an export, look for all imports of it. + * If at an export, look for all imports of it. * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. */ From e0599fd19cc690aca5fb74e18dbee5eed1b446a0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 12 Jul 2019 11:11:36 -1000 Subject: [PATCH 004/151] Instantiate contextual type for return type in getReturnTypeFromBody --- src/compiler/checker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b761606fcb3..1f8c62d0858 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19051,7 +19051,7 @@ namespace ts { // If the given contextual type contains instantiable types and if a mapper representing // return type inferences is available, instantiate those types using that mapper. - function instantiateContextualType(contextualType: Type | undefined, node: Expression, contextFlags?: ContextFlags): Type | undefined { + function instantiateContextualType(contextualType: Type | undefined, node: Node, contextFlags?: ContextFlags): Type | undefined { if (contextualType && maybeTypeOfKind(contextualType, TypeFlags.Instantiable)) { const inferenceContext = getInferenceContext(node); // If no inferences have been made, nothing is gained from instantiating as type parameters @@ -23363,7 +23363,7 @@ namespace ts { nextType && isUnitType(nextType)) { const contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : - getReturnTypeOfSignature(contextualSignature); + instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, IterationTypeKind.Yield, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, IterationTypeKind.Return, isAsync); From 044d70fc243e7f68214796611d8b93c0e31dec65 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 12 Jul 2019 17:57:05 -1000 Subject: [PATCH 005/151] Add regression tests --- .../compiler/instantiateContextualTypes.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tests/cases/compiler/instantiateContextualTypes.ts b/tests/cases/compiler/instantiateContextualTypes.ts index b81356fa91e..3165011ecff 100644 --- a/tests/cases/compiler/instantiateContextualTypes.ts +++ b/tests/cases/compiler/instantiateContextualTypes.ts @@ -140,3 +140,37 @@ declare function passContentsToFunc(outerBox: T, consumer: BoxConsumerFromOut declare const outerBoxOfString: OuterBox; passContentsToFunc(outerBoxOfString, box => box.value); + +// Repro from #32349 + +type DooDad = 'SOMETHING' | 'ELSE' ; + +class Interesting { + public compiles = () : Promise => { + return Promise.resolve().then(() => { + if (1 < 2) { + return 'SOMETHING'; + } + return 'ELSE'; + }); + }; + public doesnt = () : Promise => { + return Promise.resolve().then(() => { + return 'ELSE'; + }); + }; + public slightlyDifferentErrorMessage = () : Promise => { + return Promise.resolve().then(() => { + if (1 < 2) { + return 'SOMETHING'; + } + return 'SOMETHING'; + }); + }; +} + +// Repro from #32349 + +declare function invoke(f: () => T): T; + +let xx: 0 | 1 | 2 = invoke(() => 1); From 6f637b0870f27fcae5cfdc5ee97e212017e1ecde Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 12 Jul 2019 17:57:11 -1000 Subject: [PATCH 006/151] Accept new baselines --- .../reference/instantiateContextualTypes.js | 60 ++++++++++++ .../instantiateContextualTypes.symbols | 74 ++++++++++++++ .../instantiateContextualTypes.types | 96 +++++++++++++++++++ 3 files changed, 230 insertions(+) diff --git a/tests/baselines/reference/instantiateContextualTypes.js b/tests/baselines/reference/instantiateContextualTypes.js index 3a33b54278c..9de6bfb612c 100644 --- a/tests/baselines/reference/instantiateContextualTypes.js +++ b/tests/baselines/reference/instantiateContextualTypes.js @@ -138,6 +138,40 @@ declare function passContentsToFunc(outerBox: T, consumer: BoxConsumerFromOut declare const outerBoxOfString: OuterBox; passContentsToFunc(outerBoxOfString, box => box.value); + +// Repro from #32349 + +type DooDad = 'SOMETHING' | 'ELSE' ; + +class Interesting { + public compiles = () : Promise => { + return Promise.resolve().then(() => { + if (1 < 2) { + return 'SOMETHING'; + } + return 'ELSE'; + }); + }; + public doesnt = () : Promise => { + return Promise.resolve().then(() => { + return 'ELSE'; + }); + }; + public slightlyDifferentErrorMessage = () : Promise => { + return Promise.resolve().then(() => { + if (1 < 2) { + return 'SOMETHING'; + } + return 'SOMETHING'; + }); + }; +} + +// Repro from #32349 + +declare function invoke(f: () => T): T; + +let xx: 0 | 1 | 2 = invoke(() => 1); //// [instantiateContextualTypes.js] @@ -162,3 +196,29 @@ var N1; createElement2(InferFunctionTypes, [(foo) => "" + foo]); })(N1 || (N1 = {})); passContentsToFunc(outerBoxOfString, box => box.value); +class Interesting { + constructor() { + this.compiles = () => { + return Promise.resolve().then(() => { + if (1 < 2) { + return 'SOMETHING'; + } + return 'ELSE'; + }); + }; + this.doesnt = () => { + return Promise.resolve().then(() => { + return 'ELSE'; + }); + }; + this.slightlyDifferentErrorMessage = () => { + return Promise.resolve().then(() => { + if (1 < 2) { + return 'SOMETHING'; + } + return 'SOMETHING'; + }); + }; + } +} +let xx = invoke(() => 1); diff --git a/tests/baselines/reference/instantiateContextualTypes.symbols b/tests/baselines/reference/instantiateContextualTypes.symbols index 098be95bac5..1250edd585b 100644 --- a/tests/baselines/reference/instantiateContextualTypes.symbols +++ b/tests/baselines/reference/instantiateContextualTypes.symbols @@ -407,3 +407,77 @@ passContentsToFunc(outerBoxOfString, box => box.value); >box : Symbol(box, Decl(instantiateContextualTypes.ts, 138, 36)) >value : Symbol(value, Decl(instantiateContextualTypes.ts, 121, 20)) +// Repro from #32349 + +type DooDad = 'SOMETHING' | 'ELSE' ; +>DooDad : Symbol(DooDad, Decl(instantiateContextualTypes.ts, 138, 55)) + +class Interesting { +>Interesting : Symbol(Interesting, Decl(instantiateContextualTypes.ts, 142, 36)) + + public compiles = () : Promise => { +>compiles : Symbol(Interesting.compiles, Decl(instantiateContextualTypes.ts, 144, 19)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>DooDad : Symbol(DooDad, Decl(instantiateContextualTypes.ts, 138, 55)) + + return Promise.resolve().then(() => { +>Promise.resolve().then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) + + if (1 < 2) { + return 'SOMETHING'; + } + return 'ELSE'; + }); + }; + public doesnt = () : Promise => { +>doesnt : Symbol(Interesting.doesnt, Decl(instantiateContextualTypes.ts, 152, 3)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>DooDad : Symbol(DooDad, Decl(instantiateContextualTypes.ts, 138, 55)) + + return Promise.resolve().then(() => { +>Promise.resolve().then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) + + return 'ELSE'; + }); + }; + public slightlyDifferentErrorMessage = () : Promise => { +>slightlyDifferentErrorMessage : Symbol(Interesting.slightlyDifferentErrorMessage, Decl(instantiateContextualTypes.ts, 157, 3)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>DooDad : Symbol(DooDad, Decl(instantiateContextualTypes.ts, 138, 55)) + + return Promise.resolve().then(() => { +>Promise.resolve().then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) + + if (1 < 2) { + return 'SOMETHING'; + } + return 'SOMETHING'; + }); + }; +} + +// Repro from #32349 + +declare function invoke(f: () => T): T; +>invoke : Symbol(invoke, Decl(instantiateContextualTypes.ts, 166, 1)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 170, 24)) +>f : Symbol(f, Decl(instantiateContextualTypes.ts, 170, 27)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 170, 24)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 170, 24)) + +let xx: 0 | 1 | 2 = invoke(() => 1); +>xx : Symbol(xx, Decl(instantiateContextualTypes.ts, 172, 3)) +>invoke : Symbol(invoke, Decl(instantiateContextualTypes.ts, 166, 1)) + diff --git a/tests/baselines/reference/instantiateContextualTypes.types b/tests/baselines/reference/instantiateContextualTypes.types index 0e755e82ed3..88e6ca7e4dd 100644 --- a/tests/baselines/reference/instantiateContextualTypes.types +++ b/tests/baselines/reference/instantiateContextualTypes.types @@ -326,3 +326,99 @@ passContentsToFunc(outerBoxOfString, box => box.value); >box : InnerBox >value : string +// Repro from #32349 + +type DooDad = 'SOMETHING' | 'ELSE' ; +>DooDad : DooDad + +class Interesting { +>Interesting : Interesting + + public compiles = () : Promise => { +>compiles : () => Promise +>() : Promise => { return Promise.resolve().then(() => { if (1 < 2) { return 'SOMETHING'; } return 'ELSE'; }); } : () => Promise + + return Promise.resolve().then(() => { +>Promise.resolve().then(() => { if (1 < 2) { return 'SOMETHING'; } return 'ELSE'; }) : Promise +>Promise.resolve().then : (onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise +>Promise.resolve() : Promise +>Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>Promise : PromiseConstructor +>resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>then : (onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise +>() => { if (1 < 2) { return 'SOMETHING'; } return 'ELSE'; } : () => "SOMETHING" | "ELSE" + + if (1 < 2) { +>1 < 2 : boolean +>1 : 1 +>2 : 2 + + return 'SOMETHING'; +>'SOMETHING' : "SOMETHING" + } + return 'ELSE'; +>'ELSE' : "ELSE" + + }); + }; + public doesnt = () : Promise => { +>doesnt : () => Promise +>() : Promise => { return Promise.resolve().then(() => { return 'ELSE'; }); } : () => Promise + + return Promise.resolve().then(() => { +>Promise.resolve().then(() => { return 'ELSE'; }) : Promise +>Promise.resolve().then : (onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise +>Promise.resolve() : Promise +>Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>Promise : PromiseConstructor +>resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>then : (onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise +>() => { return 'ELSE'; } : () => "ELSE" + + return 'ELSE'; +>'ELSE' : "ELSE" + + }); + }; + public slightlyDifferentErrorMessage = () : Promise => { +>slightlyDifferentErrorMessage : () => Promise +>() : Promise => { return Promise.resolve().then(() => { if (1 < 2) { return 'SOMETHING'; } return 'SOMETHING'; }); } : () => Promise + + return Promise.resolve().then(() => { +>Promise.resolve().then(() => { if (1 < 2) { return 'SOMETHING'; } return 'SOMETHING'; }) : Promise +>Promise.resolve().then : (onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise +>Promise.resolve() : Promise +>Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>Promise : PromiseConstructor +>resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>then : (onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise +>() => { if (1 < 2) { return 'SOMETHING'; } return 'SOMETHING'; } : () => "SOMETHING" + + if (1 < 2) { +>1 < 2 : boolean +>1 : 1 +>2 : 2 + + return 'SOMETHING'; +>'SOMETHING' : "SOMETHING" + } + return 'SOMETHING'; +>'SOMETHING' : "SOMETHING" + + }); + }; +} + +// Repro from #32349 + +declare function invoke(f: () => T): T; +>invoke : (f: () => T) => T +>f : () => T + +let xx: 0 | 1 | 2 = invoke(() => 1); +>xx : 0 | 1 | 2 +>invoke(() => 1) : 1 +>invoke : (f: () => T) => T +>() => 1 : () => 1 +>1 : 1 + From d3f3c8e1135b321979f2e93b9cae3c79158cd7e8 Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Tue, 16 Jul 2019 12:00:22 -0400 Subject: [PATCH 007/151] Make it easier to read multi-line exceptions --- src/harness/fourslash.ts | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 56cc2b65508..71a07c9e248 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -948,7 +948,7 @@ namespace FourSlash { const actual = checker.typeToString(type); if (actual !== expected) { - this.raiseError(`Expected: '${expected}', actual: '${actual}'`); + this.raiseError(displayExpectedAndActualString(expected, actual)); } } @@ -1024,9 +1024,7 @@ namespace FourSlash { private assertObjectsEqual(fullActual: T, fullExpected: T, msgPrefix = ""): void { const recur = (actual: U, expected: U, path: string) => { const fail = (msg: string) => { - this.raiseError(`${msgPrefix} At ${path}: ${msg} -Expected: ${stringify(fullExpected)} -Actual: ${stringify(fullActual)}`); + this.raiseError(`${msgPrefix} At ${path}: ${msg} ${displayExpectedAndActualString(stringify(fullExpected), stringify(fullActual))}`); }; if ((actual === undefined) !== (expected === undefined)) { @@ -1058,9 +1056,7 @@ Actual: ${stringify(fullActual)}`); if (fullActual === fullExpected) { return; } - this.raiseError(`${msgPrefix} -Expected: ${stringify(fullExpected)} -Actual: ${stringify(fullActual)}`); + this.raiseError(`${msgPrefix} ${displayExpectedAndActualString(stringify(fullExpected), stringify(fullActual))}`); } recur(fullActual, fullExpected, ""); @@ -2111,9 +2107,7 @@ Actual: ${stringify(fullActual)}`); public verifyCurrentLineContent(text: string) { const actual = this.getCurrentLineContent(); if (actual !== text) { - throw new Error("verifyCurrentLineContent\n" + - "\tExpected: \"" + text + "\"\n" + - "\t Actual: \"" + actual + "\""); + throw new Error("verifyCurrentLineContent\n" + displayExpectedAndActualString(text, actual, /* quoted */ true)); } } @@ -2139,25 +2133,19 @@ Actual: ${stringify(fullActual)}`); public verifyTextAtCaretIs(text: string) { const actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); if (actual !== text) { - throw new Error("verifyTextAtCaretIs\n" + - "\tExpected: \"" + text + "\"\n" + - "\t Actual: \"" + actual + "\""); + throw new Error("verifyTextAtCaretIs\n" + displayExpectedAndActualString(text, actual, /* quoted */ true)); } } public verifyCurrentNameOrDottedNameSpanText(text: string) { const span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); if (!span) { - return this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + - "\tExpected: \"" + text + "\"\n" + - "\t Actual: undefined"); + return this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + displayExpectedAndActualString("\"" + text + "\"", "undefined")); } const actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); if (actual !== text) { - this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + - "\tExpected: \"" + text + "\"\n" + - "\t Actual: \"" + actual + "\""); + this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + displayExpectedAndActualString(text, actual, /* quoted */ true)); } } @@ -3690,7 +3678,7 @@ ${code} expected = makeWhitespaceVisible(expected); actual = makeWhitespaceVisible(actual); } - return `Expected:\n${expected}\nActual:\n${actual}`; + return displayExpectedAndActualString(expected, actual); } function differOnlyByWhitespace(a: string, b: string) { @@ -3710,6 +3698,14 @@ ${code} } } } + + function displayExpectedAndActualString(expected: string, actual: string, quoted = false) { + const expectMsg = "\x1b[1mExpected\x1b[0m\x1b[31m"; + const actualMsg = "\x1b[1mActual\x1b[0m\x1b[31m"; + const expectedString = quoted ? "\"" + expected + "\"" : expected; + const actualString = quoted ? "\"" + actual + "\"" : actual; + return `\n${expectMsg}:\n${expectedString}\n\n${actualMsg}:\n${actualString}`; + } } namespace FourSlashInterface { From 49ba408e4fed08e328dfff2614611c500ee53bb0 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 16 Jul 2019 10:14:06 -0700 Subject: [PATCH 008/151] Handle scoped package names in typing installer Fixes #32075 --- src/jsTyping/jsTyping.ts | 75 +++++++++++++------ .../unittests/tsserver/typingsInstaller.ts | 64 +++++++++++----- src/tsserver/server.ts | 2 +- src/typingsInstallerCore/typingsInstaller.ts | 29 +++---- 4 files changed, 114 insertions(+), 56 deletions(-) diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index c2b2ad3f5b3..172d041cc01 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -289,9 +289,8 @@ namespace ts.JsTyping { } - export const enum PackageNameValidationResult { + export const enum NameValidationResult { Ok, - ScopedPackagesNotSupported, EmptyName, NameTooLong, NameStartsWithDot, @@ -301,49 +300,77 @@ namespace ts.JsTyping { const maxPackageNameLength = 214; + export interface ScopedPackageNameValidationResult { + name: string; + isScopeName: boolean; + result: NameValidationResult; + } + export type PackageNameValidationResult = NameValidationResult | ScopedPackageNameValidationResult; + /** * Validates package name using rules defined at https://docs.npmjs.com/files/package.json */ export function validatePackageName(packageName: string): PackageNameValidationResult { + return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true); + } + + function validatePackageNameWorker(packageName: string, supportScopedPackage: false): NameValidationResult; + function validatePackageNameWorker(packageName: string, supportScopedPackage: true): PackageNameValidationResult; + function validatePackageNameWorker(packageName: string, supportScopedPackage: boolean): PackageNameValidationResult { if (!packageName) { - return PackageNameValidationResult.EmptyName; + return NameValidationResult.EmptyName; } if (packageName.length > maxPackageNameLength) { - return PackageNameValidationResult.NameTooLong; + return NameValidationResult.NameTooLong; } if (packageName.charCodeAt(0) === CharacterCodes.dot) { - return PackageNameValidationResult.NameStartsWithDot; + return NameValidationResult.NameStartsWithDot; } if (packageName.charCodeAt(0) === CharacterCodes._) { - return PackageNameValidationResult.NameStartsWithUnderscore; + return NameValidationResult.NameStartsWithUnderscore; } // check if name is scope package like: starts with @ and has one '/' in the middle // scoped packages are not currently supported - // TODO: when support will be added we'll need to split and check both scope and package name - if (/^@[^/]+\/[^/]+$/.test(packageName)) { - return PackageNameValidationResult.ScopedPackagesNotSupported; + if (supportScopedPackage) { + const matches = /^@([^/]+)\/([^/]+)$/.exec(packageName); + if (matches) { + const scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false); + if (scopeResult !== NameValidationResult.Ok) { + return { name: matches[1], isScopeName: true, result: scopeResult }; + } + const packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false); + if (packageResult !== NameValidationResult.Ok) { + return { name: matches[2], isScopeName: false, result: packageResult }; + } + return NameValidationResult.Ok; + } } if (encodeURIComponent(packageName) !== packageName) { - return PackageNameValidationResult.NameContainsNonURISafeCharacters; + return NameValidationResult.NameContainsNonURISafeCharacters; } - return PackageNameValidationResult.Ok; + return NameValidationResult.Ok; } export function renderPackageNameValidationFailure(result: PackageNameValidationResult, typing: string): string { + return typeof result === "object" ? + renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) : + renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false); + } + + function renderPackageNameValidationFailureWorker(typing: string, result: NameValidationResult, name: string, isScopeName: boolean): string { + const kind = isScopeName ? "Scope" : "Package"; switch (result) { - case PackageNameValidationResult.EmptyName: - return `Package name '${typing}' cannot be empty`; - case PackageNameValidationResult.NameTooLong: - return `Package name '${typing}' should be less than ${maxPackageNameLength} characters`; - case PackageNameValidationResult.NameStartsWithDot: - return `Package name '${typing}' cannot start with '.'`; - case PackageNameValidationResult.NameStartsWithUnderscore: - return `Package name '${typing}' cannot start with '_'`; - case PackageNameValidationResult.ScopedPackagesNotSupported: - return `Package '${typing}' is scoped and currently is not supported`; - case PackageNameValidationResult.NameContainsNonURISafeCharacters: - return `Package name '${typing}' contains non URI safe characters`; - case PackageNameValidationResult.Ok: + case NameValidationResult.EmptyName: + return `'${typing}':: ${kind} name '${name}' cannot be empty`; + case NameValidationResult.NameTooLong: + return `'${typing}':: ${kind} name '${name}' should be less than ${maxPackageNameLength} characters`; + case NameValidationResult.NameStartsWithDot: + return `'${typing}':: ${kind} name '${name}' cannot start with '.'`; + case NameValidationResult.NameStartsWithUnderscore: + return `'${typing}':: ${kind} name '${name}' cannot start with '_'`; + case NameValidationResult.NameContainsNonURISafeCharacters: + return `'${typing}':: ${kind} name '${name}' contains non URI safe characters`; + case NameValidationResult.Ok: return Debug.fail(); // Shouldn't have called this. default: throw Debug.assertNever(result); diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index b02adbbd094..79b4f01aa06 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -1,6 +1,6 @@ namespace ts.projectSystem { import validatePackageName = JsTyping.validatePackageName; - import PackageNameValidationResult = JsTyping.PackageNameValidationResult; + import NameValidationResult = JsTyping.NameValidationResult; interface InstallerParams { globalTypingsCacheLocation?: string; @@ -948,7 +948,8 @@ namespace ts.projectSystem { path: "/a/b/app.js", content: ` import * as fs from "fs"; - import * as commander from "commander";` + import * as commander from "commander"; + import * as component from "@ember/component";` }; const cachePath = "/a/cache"; const node = { @@ -959,14 +960,19 @@ namespace ts.projectSystem { path: cachePath + "/node_modules/@types/commander/index.d.ts", content: "export let y: string" }; + const emberComponentDirectory = "ember__component"; + const emberComponent = { + path: `${cachePath}/node_modules/@types/${emberComponentDirectory}/index.d.ts`, + content: "export let x: number" + }; const host = createServerHost([file]); const installer = new (class extends Installer { constructor() { super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("node", "commander") }); } installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) { - const installedTypings = ["@types/node", "@types/commander"]; - const typingFiles = [node, commander]; + const installedTypings = ["@types/node", "@types/commander", `@types/${emberComponentDirectory}`]; + const typingFiles = [node, commander, emberComponent]; executeCommand(this, host, installedTypings, typingFiles, cb); } })(); @@ -980,9 +986,10 @@ namespace ts.projectSystem { assert.isTrue(host.fileExists(node.path), "typings for 'node' should be created"); assert.isTrue(host.fileExists(commander.path), "typings for 'commander' should be created"); + assert.isTrue(host.fileExists(emberComponent.path), "typings for 'commander' should be created"); host.checkTimeoutQueueLengthAndRun(2); - checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path]); + checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path, emberComponent.path]); }); it("should redo resolution that resolved to '.js' file after typings are installed", () => { @@ -1263,21 +1270,44 @@ namespace ts.projectSystem { for (let i = 0; i < 8; i++) { packageName += packageName; } - assert.equal(validatePackageName(packageName), PackageNameValidationResult.NameTooLong); + assert.equal(validatePackageName(packageName), NameValidationResult.NameTooLong); }); - it("name cannot start with dot", () => { - assert.equal(validatePackageName(".foo"), PackageNameValidationResult.NameStartsWithDot); + it("package name cannot start with dot", () => { + assert.equal(validatePackageName(".foo"), NameValidationResult.NameStartsWithDot); }); - it("name cannot start with underscore", () => { - assert.equal(validatePackageName("_foo"), PackageNameValidationResult.NameStartsWithUnderscore); + it("package name cannot start with underscore", () => { + assert.equal(validatePackageName("_foo"), NameValidationResult.NameStartsWithUnderscore); }); - it("scoped packages not supported", () => { - assert.equal(validatePackageName("@scope/bar"), PackageNameValidationResult.ScopedPackagesNotSupported); + it("package non URI safe characters are not supported", () => { + assert.equal(validatePackageName(" scope "), NameValidationResult.NameContainsNonURISafeCharacters); + assert.equal(validatePackageName("; say ‘Hello from TypeScript!’ #"), NameValidationResult.NameContainsNonURISafeCharacters); + assert.equal(validatePackageName("a/b/c"), NameValidationResult.NameContainsNonURISafeCharacters); }); - it("non URI safe characters are not supported", () => { - assert.equal(validatePackageName(" scope "), PackageNameValidationResult.NameContainsNonURISafeCharacters); - assert.equal(validatePackageName("; say ‘Hello from TypeScript!’ #"), PackageNameValidationResult.NameContainsNonURISafeCharacters); - assert.equal(validatePackageName("a/b/c"), PackageNameValidationResult.NameContainsNonURISafeCharacters); + it("scoped package name is supported", () => { + assert.equal(validatePackageName("@scope/bar"), NameValidationResult.Ok); + }); + it("scoped name in scoped package name cannot start with dot", () => { + assert.deepEqual(validatePackageName("@.scope/bar"), { name: ".scope", isScopeName: true, result: NameValidationResult.NameStartsWithDot }); + assert.deepEqual(validatePackageName("@.scope/.bar"), { name: ".scope", isScopeName: true, result: NameValidationResult.NameStartsWithDot }); + }); + it("scope name in scoped package name cannot start with underscore", () => { + assert.deepEqual(validatePackageName("@_scope/bar"), { name: "_scope", isScopeName: true, result: NameValidationResult.NameStartsWithUnderscore }); + assert.deepEqual(validatePackageName("@_scope/_bar"), { name: "_scope", isScopeName: true, result: NameValidationResult.NameStartsWithUnderscore }); + }); + it("scope name in scoped package name with non URI safe characters are not supported", () => { + assert.deepEqual(validatePackageName("@ scope /bar"), { name: " scope ", isScopeName: true, result: NameValidationResult.NameContainsNonURISafeCharacters }); + assert.deepEqual(validatePackageName("@; say ‘Hello from TypeScript!’ #/bar"), { name: "; say ‘Hello from TypeScript!’ #", isScopeName: true, result: NameValidationResult.NameContainsNonURISafeCharacters }); + assert.deepEqual(validatePackageName("@ scope / bar "), { name: " scope ", isScopeName: true, result: NameValidationResult.NameContainsNonURISafeCharacters }); + }); + it("package name in scoped package name cannot start with dot", () => { + assert.deepEqual(validatePackageName("@scope/.bar"), { name: ".bar", isScopeName: false, result: NameValidationResult.NameStartsWithDot }); + }); + it("package name in scoped package name cannot start with underscore", () => { + assert.deepEqual(validatePackageName("@scope/_bar"), { name: "_bar", isScopeName: false, result: NameValidationResult.NameStartsWithUnderscore }); + }); + it("package name in scoped package name with non URI safe characters are not supported", () => { + assert.deepEqual(validatePackageName("@scope/ bar "), { name: " bar ", isScopeName: false, result: NameValidationResult.NameContainsNonURISafeCharacters }); + assert.deepEqual(validatePackageName("@scope/; say ‘Hello from TypeScript!’ #"), { name: "; say ‘Hello from TypeScript!’ #", isScopeName: false, result: NameValidationResult.NameContainsNonURISafeCharacters }); }); }); @@ -1309,7 +1339,7 @@ namespace ts.projectSystem { projectService.openClientFile(f1.path); installer.checkPendingCommands(/*expectedCount*/ 0); - assert.isTrue(messages.indexOf("Package name '; say ‘Hello from TypeScript!’ #' contains non URI safe characters") > 0, "should find package with invalid name"); + assert.isTrue(messages.indexOf("'; say ‘Hello from TypeScript!’ #':: Package name '; say ‘Hello from TypeScript!’ #' contains non URI safe characters") > 0, "should find package with invalid name"); }); }); diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 43dc4638418..a9fbf2f3b6a 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -248,7 +248,7 @@ namespace ts.server { isKnownTypesPackageName(name: string): boolean { // We want to avoid looking this up in the registry as that is expensive. So first check that it's actually an NPM package. const validationResult = JsTyping.validatePackageName(name); - if (validationResult !== JsTyping.PackageNameValidationResult.Ok) { + if (validationResult !== JsTyping.NameValidationResult.Ok) { return false; } diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index df83f1a677c..17dae3b4dcb 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -268,27 +268,28 @@ namespace ts.server.typingsInstaller { } private filterTypings(typingsToInstall: ReadonlyArray): ReadonlyArray { - return typingsToInstall.filter(typing => { - if (this.missingTypingsSet.get(typing)) { - if (this.log.isEnabled()) this.log.writeLine(`'${typing}' is in missingTypingsSet - skipping...`); - return false; + return mapDefined(typingsToInstall, typing => { + const typingKey = mangleScopedPackageName(typing); + if (this.missingTypingsSet.get(typingKey)) { + if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`); + return undefined; } const validationResult = JsTyping.validatePackageName(typing); - if (validationResult !== JsTyping.PackageNameValidationResult.Ok) { + if (validationResult !== JsTyping.NameValidationResult.Ok) { // add typing name to missing set so we won't process it again - this.missingTypingsSet.set(typing, true); + this.missingTypingsSet.set(typingKey, true); if (this.log.isEnabled()) this.log.writeLine(JsTyping.renderPackageNameValidationFailure(validationResult, typing)); - return false; + return undefined; } - if (!this.typesRegistry.has(typing)) { - if (this.log.isEnabled()) this.log.writeLine(`Entry for package '${typing}' does not exist in local types registry - skipping...`); - return false; + if (!this.typesRegistry.has(typingKey)) { + if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`); + return undefined; } - if (this.packageNameToTypingLocation.get(typing) && JsTyping.isTypingUpToDate(this.packageNameToTypingLocation.get(typing)!, this.typesRegistry.get(typing)!)) { - if (this.log.isEnabled()) this.log.writeLine(`'${typing}' already has an up-to-date typing - skipping...`); - return false; + if (this.packageNameToTypingLocation.get(typingKey) && JsTyping.isTypingUpToDate(this.packageNameToTypingLocation.get(typingKey)!, this.typesRegistry.get(typingKey)!)) { + if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`); + return undefined; } - return true; + return typingKey; }); } From 607c9c5e2681a86e1fa9807dded11248020c37a1 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 16 Jul 2019 13:13:02 -0700 Subject: [PATCH 009/151] Fix missing tokenToString for the backtick Fixes #32073 --- src/compiler/scanner.ts | 2 +- src/testRunner/unittests/publicApi.ts | 15 ++++++++++++++ .../jsdocParameterParsingInvalidName.js | 20 +++++++++++++++++++ .../jsdocParameterParsingInvalidName.symbols | 12 +++++++++++ .../jsdocParameterParsingInvalidName.types | 12 +++++++++++ .../jsdocParameterParsingInvalidName.ts | 7 +++++++ 6 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/jsdocParameterParsingInvalidName.js create mode 100644 tests/baselines/reference/jsdocParameterParsingInvalidName.symbols create mode 100644 tests/baselines/reference/jsdocParameterParsingInvalidName.types create mode 100644 tests/cases/compiler/jsdocParameterParsingInvalidName.ts diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 256e41629a1..f949893171a 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -197,6 +197,7 @@ namespace ts { "|=": SyntaxKind.BarEqualsToken, "^=": SyntaxKind.CaretEqualsToken, "@": SyntaxKind.AtToken, + "`": SyntaxKind.BacktickToken }); /* @@ -298,7 +299,6 @@ namespace ts { } const tokenStrings = makeReverseMap(textToToken); - export function tokenToString(t: SyntaxKind): string | undefined { return tokenStrings[t]; } diff --git a/src/testRunner/unittests/publicApi.ts b/src/testRunner/unittests/publicApi.ts index 17b2519c928..a31104de62a 100644 --- a/src/testRunner/unittests/publicApi.ts +++ b/src/testRunner/unittests/publicApi.ts @@ -31,3 +31,18 @@ describe("Public APIs", () => { verifyApi("tsserverlibrary.d.ts"); }); }); + +describe("Public APIs:: token to string", () => { + function assertDefinedTokenToString(initial: ts.SyntaxKind, last: ts.SyntaxKind) { + for (let t = initial; t <= last; t++) { + assert.isDefined(ts.tokenToString(t), `Expected tokenToString defined for ${ts.Debug.formatSyntaxKind(t)}`); + } + } + + it("for punctuations", () => { + assertDefinedTokenToString(ts.SyntaxKind.FirstPunctuation, ts.SyntaxKind.LastPunctuation); + }); + it("for keywords", () => { + assertDefinedTokenToString(ts.SyntaxKind.FirstKeyword, ts.SyntaxKind.LastKeyword); + }); +}); diff --git a/tests/baselines/reference/jsdocParameterParsingInvalidName.js b/tests/baselines/reference/jsdocParameterParsingInvalidName.js new file mode 100644 index 00000000000..4001ece1aec --- /dev/null +++ b/tests/baselines/reference/jsdocParameterParsingInvalidName.js @@ -0,0 +1,20 @@ +//// [jsdocParameterParsingInvalidName.ts] +class c { + /** + * @param {string} [`foo] + */ + method(foo) { + } +} + +//// [jsdocParameterParsingInvalidName.js] +var c = /** @class */ (function () { + function c() { + } + /** + * @param {string} [`foo] + */ + c.prototype.method = function (foo) { + }; + return c; +}()); diff --git a/tests/baselines/reference/jsdocParameterParsingInvalidName.symbols b/tests/baselines/reference/jsdocParameterParsingInvalidName.symbols new file mode 100644 index 00000000000..037731d2477 --- /dev/null +++ b/tests/baselines/reference/jsdocParameterParsingInvalidName.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/jsdocParameterParsingInvalidName.ts === +class c { +>c : Symbol(c, Decl(jsdocParameterParsingInvalidName.ts, 0, 0)) + + /** + * @param {string} [`foo] + */ + method(foo) { +>method : Symbol(c.method, Decl(jsdocParameterParsingInvalidName.ts, 0, 9)) +>foo : Symbol(foo, Decl(jsdocParameterParsingInvalidName.ts, 4, 11)) + } +} diff --git a/tests/baselines/reference/jsdocParameterParsingInvalidName.types b/tests/baselines/reference/jsdocParameterParsingInvalidName.types new file mode 100644 index 00000000000..d6ec561cdf2 --- /dev/null +++ b/tests/baselines/reference/jsdocParameterParsingInvalidName.types @@ -0,0 +1,12 @@ +=== tests/cases/compiler/jsdocParameterParsingInvalidName.ts === +class c { +>c : c + + /** + * @param {string} [`foo] + */ + method(foo) { +>method : (foo: any) => void +>foo : any + } +} diff --git a/tests/cases/compiler/jsdocParameterParsingInvalidName.ts b/tests/cases/compiler/jsdocParameterParsingInvalidName.ts new file mode 100644 index 00000000000..6c3c93d182e --- /dev/null +++ b/tests/cases/compiler/jsdocParameterParsingInvalidName.ts @@ -0,0 +1,7 @@ +class c { + /** + * @param {string} [`foo] + */ + method(foo) { + } +} \ No newline at end of file From d8b191a671c9cddd095d52b31c06d89222e5dd77 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 16 Jul 2019 16:29:52 -0700 Subject: [PATCH 010/151] Improve algorithm for inferring to union types --- src/compiler/checker.ts | 51 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 06395d935b7..75b12ee37bb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15458,6 +15458,7 @@ namespace ts { let visited: Map; let bivariant = false; let propagationType: Type; + let inferenceCount = 0; let allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); @@ -15561,6 +15562,7 @@ namespace ts { clearCachedInferences(inferences); } } + inferenceCount++; return; } else { @@ -15610,13 +15612,16 @@ namespace ts { inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & TypeFlags.Union) { + inferToUnionType(source, target); + } + else if (target.flags & TypeFlags.Intersection) { + inferToMultipleTypes(source, (target).types, /*isIntersection*/ true); + } else if (target.flags & TypeFlags.Conditional && !contravariant) { const targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, /*isIntersection*/ false); } - else if (target.flags & TypeFlags.UnionOrIntersection) { - inferToMultipleTypes(source, (target).types, !!(target.flags & TypeFlags.Intersection)); - } else if (source.flags & TypeFlags.Union) { // Source is a union or intersection type, infer from each constituent type const sourceTypes = (source).types; @@ -15742,6 +15747,46 @@ namespace ts { } } + function inferToUnionType(source: Type, target: UnionType) { + const sources = source.flags & TypeFlags.Union ? (source).types : [source]; + const matched = new Array(sources.length); + let typeVariableCount = 0; + // First infer to types that are not naked type variables. For each source type we + // track whether inferences were made from that particular type to some target. + for (const t of target.types) { + if (getInferenceInfoForType(t)) { + typeVariableCount++; + } + else { + for (let i = 0; i < sources.length; i++) { + const count = inferenceCount; + inferFromTypes(sources[i], t); + if (count !== inferenceCount) matched[i] = true; + } + } + } + // If there are naked type variables in the target, create a union of the source types + // from which no inferences have been made so far and infer from that union to each naked + // type variable. If there is more than one naked type variable, give lower priority to + // the inferences as they are less specific. + if (typeVariableCount > 0) { + const unmatched = flatMap(sources, (s, i) => matched![i] ? undefined : s); + if (unmatched.length) { + const s = getUnionType(unmatched); + const savePriority = priority; + if (typeVariableCount > 1) { + priority |= InferencePriority.NakedTypeVariable; + } + for (const t of target.types) { + if (getInferenceInfoForType(t)) { + inferFromTypes(s, t); + } + } + priority = savePriority; + } + } + } + function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { if (constraintType.flags & TypeFlags.Union) { let result = false; From 049618f7daf63332d7f972eb0ae4e6af3bcd55bd Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 16 Jul 2019 17:16:21 -0700 Subject: [PATCH 011/151] Get contextual type of yield from contextual signature of containing function (#32433) * Get contextual type of yield from contextual signature of containing function * Add missing baseline --- src/compiler/checker.ts | 6 +++ .../reference/generatorTypeCheck25.types | 6 +-- .../reference/generatorTypeCheck28.types | 2 +- .../reference/generatorTypeCheck45.types | 2 +- .../reference/generatorTypeCheck46.types | 2 +- .../reference/generatorTypeCheck62.types | 6 +-- .../reference/generatorTypeCheck63.types | 4 +- .../generatorYieldContextualType.symbols | 44 +++++++++++++++++++ .../generatorYieldContextualType.types | 38 ++++++++++++++++ .../types.asyncGenerators.es2018.1.types | 12 ++--- .../types.asyncGenerators.es2018.2.types | 6 +-- tests/baselines/reference/uniqueSymbols.types | 4 +- .../reference/uniqueSymbolsDeclarations.types | 4 +- .../generatorYieldContextualType.ts | 14 ++++++ 14 files changed, 126 insertions(+), 24 deletions(-) create mode 100644 tests/baselines/reference/generatorYieldContextualType.symbols create mode 100644 tests/baselines/reference/generatorYieldContextualType.types create mode 100644 tests/cases/conformance/generators/generatorYieldContextualType.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 06395d935b7..20a4246f372 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -24740,6 +24740,12 @@ namespace ts { || anyType; } + const contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Next, contextualReturnType, isAsync) + || anyType; + } + return anyType; } diff --git a/tests/baselines/reference/generatorTypeCheck25.types b/tests/baselines/reference/generatorTypeCheck25.types index d0498c2da16..12dbfeaede9 100644 --- a/tests/baselines/reference/generatorTypeCheck25.types +++ b/tests/baselines/reference/generatorTypeCheck25.types @@ -17,15 +17,15 @@ var g3: () => Iterable = function* () { >function* () { yield; yield new Bar; yield new Baz; yield *[new Bar]; yield *[new Baz];} : () => Generator yield; ->yield : any +>yield : undefined yield new Bar; ->yield new Bar : any +>yield new Bar : undefined >new Bar : Bar >Bar : typeof Bar yield new Baz; ->yield new Baz : any +>yield new Baz : undefined >new Baz : Baz >Baz : typeof Baz diff --git a/tests/baselines/reference/generatorTypeCheck28.types b/tests/baselines/reference/generatorTypeCheck28.types index 9cd4e5e82ce..6921c946a39 100644 --- a/tests/baselines/reference/generatorTypeCheck28.types +++ b/tests/baselines/reference/generatorTypeCheck28.types @@ -14,7 +14,7 @@ function* g(): IterableIterator<(x: string) => number> { >iterator : symbol yield x => x.length; ->yield x => x.length : any +>yield x => x.length : undefined >x => x.length : (x: string) => number >x : string >x.length : number diff --git a/tests/baselines/reference/generatorTypeCheck45.types b/tests/baselines/reference/generatorTypeCheck45.types index cf409241947..18d3e9a5fc2 100644 --- a/tests/baselines/reference/generatorTypeCheck45.types +++ b/tests/baselines/reference/generatorTypeCheck45.types @@ -12,7 +12,7 @@ foo("", function* () { yield x => x.length }, p => undefined); // T is fixed, sh >foo : (x: T, fun: () => Iterator<(x: T) => U, any, undefined>, fun2: (y: U) => T) => T >"" : "" >function* () { yield x => x.length } : () => Generator<(x: string) => number, void, unknown> ->yield x => x.length : any +>yield x => x.length : undefined >x => x.length : (x: string) => number >x : string >x.length : number diff --git a/tests/baselines/reference/generatorTypeCheck46.types b/tests/baselines/reference/generatorTypeCheck46.types index cd565d55911..283188193b7 100644 --- a/tests/baselines/reference/generatorTypeCheck46.types +++ b/tests/baselines/reference/generatorTypeCheck46.types @@ -24,7 +24,7 @@ foo("", function* () { >iterator : symbol yield x => x.length ->yield x => x.length : any +>yield x => x.length : undefined >x => x.length : (x: string) => number >x : string >x.length : number diff --git a/tests/baselines/reference/generatorTypeCheck62.types b/tests/baselines/reference/generatorTypeCheck62.types index be5635a07fc..ed957295c31 100644 --- a/tests/baselines/reference/generatorTypeCheck62.types +++ b/tests/baselines/reference/generatorTypeCheck62.types @@ -32,7 +32,7 @@ export function strategy(stratName: string, gen: (a: T >stratName : string } yield next; ->yield next : any +>yield next : undefined >next : T } } @@ -70,7 +70,7 @@ export const Nothing2: Strategy = strategy("Nothing", function*(state: St >state : State yield state; ->yield state : any +>yield state : undefined >state : State }); @@ -84,7 +84,7 @@ export const Nothing3: Strategy = strategy("Nothing", function* (state: S >state : State yield ; ->yield : any +>yield : undefined return state; >state : State diff --git a/tests/baselines/reference/generatorTypeCheck63.types b/tests/baselines/reference/generatorTypeCheck63.types index 8a1d03dcb16..64d67083e61 100644 --- a/tests/baselines/reference/generatorTypeCheck63.types +++ b/tests/baselines/reference/generatorTypeCheck63.types @@ -32,7 +32,7 @@ export function strategy(stratName: string, gen: (a: T >stratName : string } yield next; ->yield next : any +>yield next : undefined >next : T } } @@ -97,7 +97,7 @@ export const Nothing3: Strategy = strategy("Nothing", function* (state: S >state : State yield state; ->yield state : any +>yield state : undefined >state : State return 1; diff --git a/tests/baselines/reference/generatorYieldContextualType.symbols b/tests/baselines/reference/generatorYieldContextualType.symbols new file mode 100644 index 00000000000..80d20b90d75 --- /dev/null +++ b/tests/baselines/reference/generatorYieldContextualType.symbols @@ -0,0 +1,44 @@ +=== tests/cases/conformance/generators/generatorYieldContextualType.ts === +declare function f1(gen: () => Generator): void; +>f1 : Symbol(f1, Decl(generatorYieldContextualType.ts, 0, 0)) +>T : Symbol(T, Decl(generatorYieldContextualType.ts, 0, 20)) +>R : Symbol(R, Decl(generatorYieldContextualType.ts, 0, 22)) +>S : Symbol(S, Decl(generatorYieldContextualType.ts, 0, 25)) +>gen : Symbol(gen, Decl(generatorYieldContextualType.ts, 0, 29)) +>Generator : Symbol(Generator, Decl(lib.es2015.generator.d.ts, --, --)) +>R : Symbol(R, Decl(generatorYieldContextualType.ts, 0, 22)) +>T : Symbol(T, Decl(generatorYieldContextualType.ts, 0, 20)) +>S : Symbol(S, Decl(generatorYieldContextualType.ts, 0, 25)) + +f1<0, 0, 1>(function* () { +>f1 : Symbol(f1, Decl(generatorYieldContextualType.ts, 0, 0)) + + const a = yield 0; +>a : Symbol(a, Decl(generatorYieldContextualType.ts, 2, 6)) + + return 0; +}); + +declare function f2(gen: () => Generator | AsyncGenerator): void; +>f2 : Symbol(f2, Decl(generatorYieldContextualType.ts, 4, 3)) +>T : Symbol(T, Decl(generatorYieldContextualType.ts, 6, 20)) +>R : Symbol(R, Decl(generatorYieldContextualType.ts, 6, 22)) +>S : Symbol(S, Decl(generatorYieldContextualType.ts, 6, 25)) +>gen : Symbol(gen, Decl(generatorYieldContextualType.ts, 6, 29)) +>Generator : Symbol(Generator, Decl(lib.es2015.generator.d.ts, --, --)) +>R : Symbol(R, Decl(generatorYieldContextualType.ts, 6, 22)) +>T : Symbol(T, Decl(generatorYieldContextualType.ts, 6, 20)) +>S : Symbol(S, Decl(generatorYieldContextualType.ts, 6, 25)) +>AsyncGenerator : Symbol(AsyncGenerator, Decl(lib.es2018.asyncgenerator.d.ts, --, --)) +>R : Symbol(R, Decl(generatorYieldContextualType.ts, 6, 22)) +>T : Symbol(T, Decl(generatorYieldContextualType.ts, 6, 20)) +>S : Symbol(S, Decl(generatorYieldContextualType.ts, 6, 25)) + +f2<0, 0, 1>(async function* () { +>f2 : Symbol(f2, Decl(generatorYieldContextualType.ts, 4, 3)) + + const a = yield 0; +>a : Symbol(a, Decl(generatorYieldContextualType.ts, 8, 6)) + + return 0; +}); diff --git a/tests/baselines/reference/generatorYieldContextualType.types b/tests/baselines/reference/generatorYieldContextualType.types new file mode 100644 index 00000000000..5caccffa933 --- /dev/null +++ b/tests/baselines/reference/generatorYieldContextualType.types @@ -0,0 +1,38 @@ +=== tests/cases/conformance/generators/generatorYieldContextualType.ts === +declare function f1(gen: () => Generator): void; +>f1 : (gen: () => Generator) => void +>gen : () => Generator + +f1<0, 0, 1>(function* () { +>f1<0, 0, 1>(function* () { const a = yield 0; return 0;}) : void +>f1 : (gen: () => Generator) => void +>function* () { const a = yield 0; return 0;} : () => Generator<0, 0, unknown> + + const a = yield 0; +>a : 1 +>yield 0 : 1 +>0 : 0 + + return 0; +>0 : 0 + +}); + +declare function f2(gen: () => Generator | AsyncGenerator): void; +>f2 : (gen: () => Generator | AsyncGenerator) => void +>gen : () => Generator | AsyncGenerator + +f2<0, 0, 1>(async function* () { +>f2<0, 0, 1>(async function* () { const a = yield 0; return 0;}) : void +>f2 : (gen: () => Generator | AsyncGenerator) => void +>async function* () { const a = yield 0; return 0;} : () => AsyncGenerator<0, 0, unknown> + + const a = yield 0; +>a : 1 +>yield 0 : 1 +>0 : 0 + + return 0; +>0 : 0 + +}); diff --git a/tests/baselines/reference/types.asyncGenerators.es2018.1.types b/tests/baselines/reference/types.asyncGenerators.es2018.1.types index ad35f2a796f..24da9312c15 100644 --- a/tests/baselines/reference/types.asyncGenerators.es2018.1.types +++ b/tests/baselines/reference/types.asyncGenerators.es2018.1.types @@ -78,7 +78,7 @@ const assignability1: () => AsyncIterableIterator = async function * () >async function * () { yield 1;} : () => AsyncGenerator yield 1; ->yield 1 : any +>yield 1 : undefined >1 : 1 }; @@ -87,7 +87,7 @@ const assignability2: () => AsyncIterableIterator = async function * () >async function * () { yield Promise.resolve(1);} : () => AsyncGenerator yield Promise.resolve(1); ->yield Promise.resolve(1) : any +>yield Promise.resolve(1) : undefined >Promise.resolve(1) : Promise >Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } >Promise : PromiseConstructor @@ -138,7 +138,7 @@ const assignability6: () => AsyncIterable = async function * () { >async function * () { yield 1;} : () => AsyncGenerator yield 1; ->yield 1 : any +>yield 1 : undefined >1 : 1 }; @@ -147,7 +147,7 @@ const assignability7: () => AsyncIterable = async function * () { >async function * () { yield Promise.resolve(1);} : () => AsyncGenerator yield Promise.resolve(1); ->yield Promise.resolve(1) : any +>yield Promise.resolve(1) : undefined >Promise.resolve(1) : Promise >Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } >Promise : PromiseConstructor @@ -198,7 +198,7 @@ const assignability11: () => AsyncIterator = async function * () { >async function * () { yield 1;} : () => AsyncGenerator yield 1; ->yield 1 : any +>yield 1 : undefined >1 : 1 }; @@ -207,7 +207,7 @@ const assignability12: () => AsyncIterator = async function * () { >async function * () { yield Promise.resolve(1);} : () => AsyncGenerator yield Promise.resolve(1); ->yield Promise.resolve(1) : any +>yield Promise.resolve(1) : undefined >Promise.resolve(1) : Promise >Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } >Promise : PromiseConstructor diff --git a/tests/baselines/reference/types.asyncGenerators.es2018.2.types b/tests/baselines/reference/types.asyncGenerators.es2018.2.types index 23bf7225eb9..022ddd297a2 100644 --- a/tests/baselines/reference/types.asyncGenerators.es2018.2.types +++ b/tests/baselines/reference/types.asyncGenerators.es2018.2.types @@ -32,7 +32,7 @@ const assignability1: () => AsyncIterableIterator = async function * () >async function * () { yield "a";} : () => AsyncGenerator yield "a"; ->yield "a" : any +>yield "a" : undefined >"a" : "a" }; @@ -65,7 +65,7 @@ const assignability4: () => AsyncIterable = async function * () { >async function * () { yield "a";} : () => AsyncGenerator yield "a"; ->yield "a" : any +>yield "a" : undefined >"a" : "a" }; @@ -98,7 +98,7 @@ const assignability7: () => AsyncIterator = async function * () { >async function * () { yield "a";} : () => AsyncGenerator yield "a"; ->yield "a" : any +>yield "a" : undefined >"a" : "a" }; diff --git a/tests/baselines/reference/uniqueSymbols.types b/tests/baselines/reference/uniqueSymbols.types index da2f9895218..02ededf7b1f 100644 --- a/tests/baselines/reference/uniqueSymbols.types +++ b/tests/baselines/reference/uniqueSymbols.types @@ -839,7 +839,7 @@ const o3: Context = { >method3 : () => AsyncGenerator yield s; // yield type should not widen due to contextual type ->yield s : any +>yield s : undefined >s : unique symbol }, @@ -847,7 +847,7 @@ const o3: Context = { >method4 : () => Generator yield s; // yield type should not widen due to contextual type ->yield s : any +>yield s : undefined >s : unique symbol }, diff --git a/tests/baselines/reference/uniqueSymbolsDeclarations.types b/tests/baselines/reference/uniqueSymbolsDeclarations.types index b8c32385f4b..db198153153 100644 --- a/tests/baselines/reference/uniqueSymbolsDeclarations.types +++ b/tests/baselines/reference/uniqueSymbolsDeclarations.types @@ -832,7 +832,7 @@ const o4: Context = { >method3 : () => AsyncGenerator yield s; // yield type should not widen due to contextual type ->yield s : any +>yield s : undefined >s : unique symbol }, @@ -840,7 +840,7 @@ const o4: Context = { >method4 : () => Generator yield s; // yield type should not widen due to contextual type ->yield s : any +>yield s : undefined >s : unique symbol }, diff --git a/tests/cases/conformance/generators/generatorYieldContextualType.ts b/tests/cases/conformance/generators/generatorYieldContextualType.ts new file mode 100644 index 00000000000..20cad6a9189 --- /dev/null +++ b/tests/cases/conformance/generators/generatorYieldContextualType.ts @@ -0,0 +1,14 @@ +// @target: esnext +// @strict: true +// @noEmit: true +declare function f1(gen: () => Generator): void; +f1<0, 0, 1>(function* () { + const a = yield 0; + return 0; +}); + +declare function f2(gen: () => Generator | AsyncGenerator): void; +f2<0, 0, 1>(async function* () { + const a = yield 0; + return 0; +}); \ No newline at end of file From e6c723dd2aefc851642ba3b7c534986ae33f3d9b Mon Sep 17 00:00:00 2001 From: csigs Date: Wed, 17 Jul 2019 16:10:08 +0000 Subject: [PATCH 012/151] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index 2c25256b224..07839d24475 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,4 +1,4 @@ - + @@ -3301,7 +3301,7 @@ - + @@ -4123,7 +4123,7 @@ - + From 246610957772c8801457ec9c8f32b0686edc0716 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 17 Jul 2019 13:07:10 -0700 Subject: [PATCH 013/151] Fix build/lint due to differences in master and LKG (#32450) --- src/compiler/emitter.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index a1207c9b892..8681a452e2a 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -411,7 +411,11 @@ namespace ts { } ); if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === SyntaxKind.SourceFile) { - const sourceFile = declarationTransform.transformed[0] as SourceFile; + // Improved narrowing in master/3.6 makes this cast unnecessary, triggering a lint rule. + // But at the same time, the LKG (3.5) necessitates it because it doesn’t narrow. + // Once the LKG is updated to 3.6, this comment, the cast to `SourceFile`, and the + // tslint directive can be all be removed. + const sourceFile = declarationTransform.transformed[0] as SourceFile; // tslint:disable-line exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } } From 8f2ed0ded88a978c283eab9a9184729b6f7e009f Mon Sep 17 00:00:00 2001 From: Milosz Piechocki Date: Wed, 17 Jul 2019 22:22:53 +0200 Subject: [PATCH 014/151] addTypeToIntersection performance improvement (#32388) --- src/compiler/checker.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 20a4246f372..1d6b9e842cc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9890,7 +9890,7 @@ namespace ts { return links.resolvedType; } - function addTypeToIntersection(typeSet: Type[], includes: TypeFlags, type: Type) { + function addTypeToIntersection(typeSet: Map, includes: TypeFlags, type: Type) { const flags = type.flags; if (flags & TypeFlags.Intersection) { return addTypesToIntersection(typeSet, includes, (type).types); @@ -9898,20 +9898,20 @@ namespace ts { if (isEmptyAnonymousObjectType(type)) { if (!(includes & TypeFlags.IncludesEmptyObject)) { includes |= TypeFlags.IncludesEmptyObject; - typeSet.push(type); + typeSet.set(type.id.toString(), type); } } else { if (flags & TypeFlags.AnyOrUnknown) { if (type === wildcardType) includes |= TypeFlags.IncludesWildcard; } - else if ((strictNullChecks || !(flags & TypeFlags.Nullable)) && !contains(typeSet, type)) { + else if ((strictNullChecks || !(flags & TypeFlags.Nullable)) && !typeSet.has(type.id.toString())) { if (type.flags & TypeFlags.Unit && includes & TypeFlags.Unit) { // We have seen two distinct unit types which means we should reduce to an // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen. includes |= TypeFlags.NonPrimitive; } - typeSet.push(type); + typeSet.set(type.id.toString(), type); } includes |= flags & TypeFlags.IncludesMask; } @@ -9920,7 +9920,7 @@ namespace ts { // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet: Type[], includes: TypeFlags, types: ReadonlyArray) { + function addTypesToIntersection(typeSet: Map, includes: TypeFlags, types: ReadonlyArray) { for (const type of types) { includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } @@ -10027,8 +10027,9 @@ namespace ts { // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types: ReadonlyArray, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { - const typeSet: Type[] = []; - const includes = addTypesToIntersection(typeSet, 0, types); + const typeMembershipMap: Map = createMap(); + const includes = addTypesToIntersection(typeMembershipMap, 0, types); + const typeSet: Type[] = arrayFrom(typeMembershipMap.values()); // An intersection type is considered empty if it contains // the type never, or // more than one unit type or, From ddbf7e198d8a01967f2d20366dfeb8ad07a28543 Mon Sep 17 00:00:00 2001 From: 0verk1ll Date: Wed, 17 Jul 2019 16:57:25 -0400 Subject: [PATCH 015/151] Add Semicolons to Gulpfile.js --- Gulpfile.js | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Gulpfile.js b/Gulpfile.js index 42987e4fd8d..d5c40a1625d 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -41,7 +41,7 @@ const generateLibs = () => { .pipe(concat(relativeTarget, { newLine: "\n\n" })) .pipe(dest("built/local")))); }; -task("lib", generateLibs) +task("lib", generateLibs); task("lib").description = "Builds the library targets"; const cleanLib = () => del(libs.map(lib => lib.target)); @@ -168,7 +168,7 @@ task("services", series(preBuild, buildServices)); task("services").description = "Builds the language service"; task("services").flags = { " --built": "Compile using the built version of the compiler." -} +}; const cleanServices = async () => { if (fs.existsSync("built/local/typescriptServices.tsconfig.json")) { @@ -200,14 +200,14 @@ task("watch-services", series(preBuild, parallel(watchLib, watchDiagnostics, wat task("watch-services").description = "Watches for changes and rebuild language service only"; task("watch-services").flags = { " --built": "Compile using the built version of the compiler." -} +}; const buildServer = () => buildProject("src/tsserver", cmdLineOptions); task("tsserver", series(preBuild, buildServer)); task("tsserver").description = "Builds the language server"; task("tsserver").flags = { " --built": "Compile using the built version of the compiler." -} +}; const cleanServer = () => cleanProject("src/tsserver"); cleanTasks.push(cleanServer); @@ -219,13 +219,13 @@ task("watch-tsserver", series(preBuild, parallel(watchLib, watchDiagnostics, wat task("watch-tsserver").description = "Watch for changes and rebuild the language server only"; task("watch-tsserver").flags = { " --built": "Compile using the built version of the compiler." -} +}; task("min", series(preBuild, parallel(buildTsc, buildServer))); task("min").description = "Builds only tsc and tsserver"; task("min").flags = { " --built": "Compile using the built version of the compiler." -} +}; task("clean-min", series(cleanTsc, cleanServer)); task("clean-min").description = "Cleans outputs for tsc and tsserver"; @@ -234,7 +234,7 @@ task("watch-min", series(preBuild, parallel(watchLib, watchDiagnostics, watchTsc task("watch-min").description = "Watches for changes to a tsc and tsserver only"; task("watch-min").flags = { " --built": "Compile using the built version of the compiler." -} +}; const buildLssl = (() => { // build tsserverlibrary.out.js @@ -268,7 +268,7 @@ task("lssl", series(preBuild, buildLssl)); task("lssl").description = "Builds language service server library"; task("lssl").flags = { " --built": "Compile using the built version of the compiler." -} +}; const cleanLssl = async () => { if (fs.existsSync("built/local/tsserverlibrary.tsconfig.json")) { @@ -302,14 +302,14 @@ task("watch-lssl", series(preBuild, parallel(watchLib, watchDiagnostics, watchLs task("watch-lssl").description = "Watch for changes and rebuild tsserverlibrary only"; task("watch-lssl").flags = { " --built": "Compile using the built version of the compiler." -} +}; const buildTests = () => buildProject("src/testRunner"); task("tests", series(preBuild, parallel(buildLssl, buildTests))); task("tests").description = "Builds the test infrastructure"; task("tests").flags = { " --built": "Compile using the built version of the compiler." -} +}; const cleanTests = () => cleanProject("src/testRunner"); cleanTasks.push(cleanTests); @@ -381,13 +381,13 @@ task("local", series(buildFoldStart, preBuild, parallel(localize, buildTsc, buil task("local").description = "Builds the full compiler and services"; task("local").flags = { " --built": "Compile using the built version of the compiler." -} +}; task("watch-local", series(preBuild, parallel(watchLib, watchDiagnostics, watchTsc, watchServices, watchServer, watchLssl))); task("watch-local").description = "Watches for changes to projects in src/ (but does not execute tests)."; task("watch-local").flags = { " --built": "Compile using the built version of the compiler." -} +}; const generateCodeCoverage = () => exec("istanbul", ["cover", "node_modules/mocha/bin/_mocha", "--", "-R", "min", "-t", "" + cmdLineOptions.testTimeout, "built/local/run.js"]); task("generate-code-coverage", series(preBuild, buildTests, generateCodeCoverage)); @@ -417,7 +417,7 @@ task("runtests").flags = { " --built": "Compile using the built version of the compiler.", " --shards": "Total number of shards running tests (default: 1)", " --shardId": "1-based ID of this shard (default: 1)", -} +}; const runTestsParallel = () => runConsoleTests("built/local/run.js", "min", /*runInParallel*/ true, /*watchMode*/ false); task("runtests-parallel", series(preBuild, preTest, runTestsParallel, postTest)); @@ -478,7 +478,7 @@ task("tsc-instrumented", series(lkgPreBuild, parallel(localize, buildTsc, buildS task("tsc-instrumented").description = "Builds an instrumented tsc.js"; task("tsc-instrumented").flags = { "-t --tests=": "The test to run." -} +}; // TODO(rbuckton): Determine if we still need this task. Depending on a relative // path here seems like a bad idea. @@ -533,7 +533,7 @@ task("LKG", series(lkgPreBuild, parallel(localize, buildTsc, buildServer, buildS task("LKG").description = "Makes a new LKG out of the built js files"; task("LKG").flags = { " --built": "Compile using the built version of the compiler.", -} +}; const generateSpec = () => exec("cscript", ["//nologo", "scripts/word2md.js", path.resolve("doc/TypeScript Language Specification.docx"), path.resolve("doc/spec.md")]); task("generate-spec", series(buildScripts, generateSpec)); @@ -542,15 +542,15 @@ task("generate-spec").description = "Generates a Markdown version of the Languag task("clean", series(parallel(cleanTasks), cleanBuilt)); task("clean").description = "Cleans build outputs"; -const configureNightly = () => exec(process.execPath, ["scripts/configurePrerelease.js", "dev", "package.json", "src/compiler/core.ts"]) +const configureNightly = () => exec(process.execPath, ["scripts/configurePrerelease.js", "dev", "package.json", "src/compiler/core.ts"]); task("configure-nightly", series(buildScripts, configureNightly)); task("configure-nightly").description = "Runs scripts/configurePrerelease.ts to prepare a build for nightly publishing"; -const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.js", "insiders", "package.json", "src/compiler/core.ts"]) +const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.js", "insiders", "package.json", "src/compiler/core.ts"]); task("configure-insiders", series(buildScripts, configureInsiders)); task("configure-insiders").description = "Runs scripts/configurePrerelease.ts to prepare a build for insiders publishing"; -const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.js", "experimental", "package.json", "src/compiler/core.ts"]) +const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.js", "experimental", "package.json", "src/compiler/core.ts"]); task("configure-experimental", series(buildScripts, configureExperimental)); task("configure-experimental").description = "Runs scripts/configurePrerelease.ts to prepare a build for experimental publishing"; From 387c917765793773a6f7184bab84e6f5956f44fc Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 17 Jul 2019 14:02:18 -0700 Subject: [PATCH 016/151] =?UTF-8?q?Revert=20"Proposal:=20If=20there?= =?UTF-8?q?=E2=80=99s=20a=20package.json,=20only=20auto-import=20things=20?= =?UTF-8?q?in=20it,=20more=20or=20less=20(#31893)"=20(#32448)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 60a1b1dc1a93ca792cf12bb0432cf7bc134c3ad1. --- src/compiler/utilities.ts | 2 +- src/harness/fourslash.ts | 2 +- src/services/codefixes/importFixes.ts | 124 +------------- src/services/completions.ts | 152 ++++-------------- src/services/services.ts | 2 +- src/services/stringCompletions.ts | 49 ++++++ src/services/utilities.ts | 49 ------ ...rt_filteredByPackageJson_@typesImplicit.ts | 44 ----- ...Import_filteredByPackageJson_@typesOnly.ts | 44 ----- ...onsImport_filteredByPackageJson_ambient.ts | 30 ---- ...ionsImport_filteredByPackageJson_direct.ts | 46 ------ ...ionsImport_filteredByPackageJson_nested.ts | 66 -------- ...nsImport_filteredByPackageJson_reexport.ts | 58 ------- ...sImport_filteredByPackageJson_reexport2.ts | 58 ------- ...sImport_filteredByPackageJson_reexport3.ts | 48 ------ ...sImport_filteredByPackageJson_reexport4.ts | 57 ------- .../fourslash/completionsImport_ofAlias.ts | 17 +- .../importNameCodeFixNewImportNodeModules8.ts | 2 +- 18 files changed, 98 insertions(+), 752 deletions(-) delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesImplicit.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesOnly.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_ambient.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_direct.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_nested.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport2.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport3.ts delete mode 100644 tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport4.ts diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index fb5c69c6375..f3282d43723 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -7485,7 +7485,7 @@ namespace ts { export function getDirectoryPath(path: Path): Path; /** * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` - * except that we support URLs as well. + * except that we support URL's as well. * * ```ts * getDirectoryPath("/path/to/file.ext") === "/path/to" diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 919352e1391..aa764e74cdc 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -798,7 +798,7 @@ namespace FourSlash { const name = typeof include === "string" ? include : include.name; const found = nameToEntries.get(name); if (!found) throw this.raiseError(`No completion ${name} found`); - assert(found.length === 1, `Must use 'exact' for multiple completions with same name: '${name}'`); + assert(found.length === 1); // Must use 'exact' for multiple completions with same name this.verifyCompletionEntry(ts.first(found), include); } } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 2fcc8cf5ccb..8006d1a0cfd 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -283,25 +283,13 @@ namespace ts.codefix { preferences: UserPreferences, ): ReadonlyArray { const isJs = isSourceFileJS(sourceFile); - const { allowsImporting } = createLazyPackageJsonDependencyReader(sourceFile, host); const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map((moduleSpecifier): FixAddNewImport | FixUseImportType => // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. exportedSymbolIsTypeOnly && isJs ? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.assertDefined(position) } : { kind: ImportFixKind.AddNew, moduleSpecifier, importKind })); - - // Sort by presence in package.json, then shortest paths first - return sort(choicesForEachExportingModule, (a, b) => { - const allowsImportingA = allowsImporting(a.moduleSpecifier); - const allowsImportingB = allowsImporting(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); + // Sort to keep the shortest paths first + return sort(choicesForEachExportingModule, (a, b) => a.moduleSpecifier.length - b.moduleSpecifier.length); } function getFixesForAddImport( @@ -392,8 +380,7 @@ namespace ts.codefix { // "default" is a keyword and not a legal identifier for the import, so we don't expect it here Debug.assert(symbolName !== InternalSymbolName.Default); - const exportInfos = getExportInfos(symbolName, getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, preferences, host); - const fixes = arrayFrom(flatMapIterator(exportInfos.entries(), ([_, exportInfos]) => + const fixes = arrayFrom(flatMapIterator(getExportInfos(symbolName, getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), ([_, exportInfos]) => getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences))); return { fixes, symbolName }; } @@ -406,8 +393,6 @@ namespace ts.codefix { sourceFile: SourceFile, checker: TypeChecker, program: Program, - preferences: UserPreferences, - host: LanguageServiceHost ): ReadonlyMap> { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). @@ -415,7 +400,7 @@ namespace ts.codefix { function addSymbol(moduleSymbol: Symbol, exportedSymbol: Symbol, importKind: ImportKind): void { originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } - forEachExternalModuleToImportFrom(checker, host, preferences, program.redirectTargetsMap, sourceFile, program.getSourceFiles(), moduleSymbol => { + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), moduleSymbol => { cancellationToken.throwIfCancellationRequested(); const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); @@ -576,44 +561,12 @@ namespace ts.codefix { return some(declarations, decl => !!(getMeaningFromDeclaration(decl) & meaning)); } - export function forEachExternalModuleToImportFrom(checker: TypeChecker, host: LanguageServiceHost, preferences: UserPreferences, redirectTargetsMap: RedirectTargetsMap, from: SourceFile, allSourceFiles: ReadonlyArray, cb: (module: Symbol) => void) { - const { allowsImporting } = createLazyPackageJsonDependencyReader(from, host); - const compilerOptions = host.getCompilationSettings(); - const getCanonicalFileName = hostGetCanonicalFileName(host); + export function forEachExternalModuleToImportFrom(checker: TypeChecker, from: SourceFile, allSourceFiles: ReadonlyArray, cb: (module: Symbol) => void) { forEachExternalModule(checker, allSourceFiles, (module, sourceFile) => { - if (sourceFile === undefined && allowsImporting(stripQuotes(module.getName()))) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { cb(module); } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { - const moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); - if (!moduleSpecifier || allowsImporting(moduleSpecifier)) { - cb(module); - } - } }); - - function getNodeModulesPackageNameFromFileName(importedFileName: string): string | undefined { - const specifier = moduleSpecifiers.getModuleSpecifier( - compilerOptions, - from, - toPath(from.fileName, /*basePath*/ undefined, getCanonicalFileName), - importedFileName, - host, - allSourceFiles, - preferences, - redirectTargetsMap); - - // Paths here are not node_modules, so we don’t care about them; - // returning anything will trigger a lookup in package.json. - if (!pathIsRelative(specifier) && !isRootedDiskPath(specifier)) { - const components = getPathComponents(getPackageNameFromTypesPackageName(specifier)).slice(1); - // Scoped packages - if (startsWith(components[0], "@")) { - return `${components[0]}/${components[1]}`; - } - return components[0]; - } - } } function forEachExternalModule(checker: TypeChecker, allSourceFiles: ReadonlyArray, cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) { @@ -667,69 +620,4 @@ namespace ts.codefix { // Need `|| "_"` to ensure result isn't empty. return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; } - - function createLazyPackageJsonDependencyReader(fromFile: SourceFile, host: LanguageServiceHost) { - const packageJsonPaths = findPackageJsons(getDirectoryPath(fromFile.fileName), host); - const dependencyIterator = readPackageJsonDependencies(host, packageJsonPaths); - let seenDeps: Map | undefined; - let usesNodeCoreModules: boolean | undefined; - return { allowsImporting }; - - function containsDependency(dependency: string) { - if ((seenDeps || (seenDeps = createMap())).has(dependency)) { - return true; - } - let packageName: string | void; - while (packageName = dependencyIterator.next().value) { - seenDeps.set(packageName, true); - if (packageName === dependency) { - return true; - } - } - return false; - } - - function allowsImporting(moduleSpecifier: string): boolean { - if (!packageJsonPaths.length) { - return true; - } - - // If we’re in JavaScript, it can be difficult to tell whether the user wants to import - // from Node core modules or not. We can start by seeing if the user is actually using - // any node core modules, as opposed to simply having @types/node accidentally as a - // dependency of a dependency. - if (isSourceFileJS(fromFile) && JsTyping.nodeCoreModules.has(moduleSpecifier)) { - if (usesNodeCoreModules === undefined) { - usesNodeCoreModules = consumesNodeCoreModules(fromFile); - } - if (usesNodeCoreModules) { - return true; - } - } - - return containsDependency(moduleSpecifier) - || containsDependency(getTypesPackageName(moduleSpecifier)); - } - } - - function *readPackageJsonDependencies(host: LanguageServiceHost, packageJsonPaths: string[]) { - type PackageJson = Record | undefined>; - const dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies"] as const; - for (const fileName of packageJsonPaths) { - const content = readJson(fileName, { readFile: host.readFile ? host.readFile.bind(host) : sys.readFile }) as PackageJson; - for (const key of dependencyKeys) { - const dependencies = content[key]; - if (!dependencies) { - continue; - } - for (const packageName in dependencies) { - yield packageName; - } - } - } - } - - function consumesNodeCoreModules(sourceFile: SourceFile): boolean { - return some(sourceFile.imports, ({ text }) => JsTyping.nodeCoreModules.has(text)); - } } diff --git a/src/services/completions.ts b/src/services/completions.ts index d7b40d14587..b5c412a788a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -64,7 +64,7 @@ namespace ts.Completions { return getLabelCompletionAtPosition(contextToken.parent); } - const completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined, host); + const completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); if (!completionData) { return undefined; } @@ -407,10 +407,10 @@ namespace ts.Completions { previousToken: Node | undefined; readonly isJsxInitializer: IsJsxInitializer; } - function getSymbolCompletionFromEntryId(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, host: LanguageServiceHost + function getSymbolCompletionFromEntryId(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, ): SymbolCompletion | { type: "request", request: Request } | { type: "literal", literal: string | number | PseudoBigInt } | { type: "none" } { const compilerOptions = program.getCompilerOptions(); - const completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); + const completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } @@ -472,7 +472,7 @@ namespace ts.Completions { } // Compute all the completion symbols again. - const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host); + const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); switch (symbolCompletion.type) { case "request": { const { request } = symbolCompletion; @@ -557,8 +557,8 @@ namespace ts.Completions { return { sourceDisplay: [textPart(moduleSpecifier)], codeActions: [codeAction] }; } - export function getCompletionEntrySymbol(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, host: LanguageServiceHost): Symbol | undefined { - const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host); + export function getCompletionEntrySymbol(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier): Symbol | undefined { + const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); return completion.type === "symbol" ? completion.symbol : undefined; } @@ -657,7 +657,6 @@ namespace ts.Completions { position: number, preferences: Pick, detailsEntryId: CompletionEntryIdentifier | undefined, - host: LanguageServiceHost ): CompletionData | Request | undefined { const typeChecker = program.getTypeChecker(); @@ -1150,7 +1149,7 @@ namespace ts.Completions { } if (shouldOfferImportCompletions()) { - getSymbolsFromOtherSourceFileExports(symbols, previousToken && isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target!, host); + getSymbolsFromOtherSourceFileExports(symbols, previousToken && isIdentifier(previousToken) ? previousToken.text : "", program.getCompilerOptions().target!); } filterGlobalCompletion(symbols); } @@ -1268,64 +1267,12 @@ namespace ts.Completions { typeChecker.getExportsOfModule(sym).some(e => symbolCanBeReferencedAtTypeLocation(e, seenModules)); } - /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” - * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but - * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, - * if and only if the the first can be imported (it may be excluded due to package.json filtering in - * `codefix.forEachExternalModuleToImportFrom`). - * - * Example. Imagine a chain of node_modules re-exporting one original symbol: - * - * ```js - * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js - * +-----------------------+ +--------------------------+ +--------------------------+ - * | | | | | | - * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; | - * | | | | | | - * +-----------------------+ +--------------------------+ +--------------------------+ - * ``` - * - * Also imagine three buckets, which we’ll reference soon: - * - * ```md - * | | | | | | - * | **Bucket A** | | **Bucket B** | | **Bucket C** | - * | Symbols to | | Aliases to symbols | | Symbols to return | - * | definitely | | in Buckets A or C | | if nothing better | - * | return | | (don’t return these) | | comes along | - * |__________________| |______________________| |___________________| - * ``` - * - * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it - * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not - * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we - * may not be sure whether or not it should go in the list. So, we’ll take the following steps: - * - * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is - * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B - * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C. - * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'. - * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z' - * should never be returned in the final list, so put it in Bucket B. - * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so - * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out. - * Put this symbol in Bucket A. - * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t - * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move - * everything from Bucket C to Bucket A. - * - * Note: Bucket A is passed in as the parameter `symbols` and mutated. - */ - function getSymbolsFromOtherSourceFileExports(/** Bucket A */ symbols: Symbol[], tokenText: string, target: ScriptTarget, host: LanguageServiceHost): void { + function getSymbolsFromOtherSourceFileExports(symbols: Symbol[], tokenText: string, target: ScriptTarget): void { const tokenTextLowerCase = tokenText.toLowerCase(); - const seenResolvedModules = createMap(); - /** Bucket B */ - const aliasesToAlreadyIncludedSymbols = createMap(); - /** Bucket C */ - const aliasesToReturnIfOriginalsAreMissing = createMap<{ alias: Symbol, moduleSymbol: Symbol }>(); - codefix.forEachExternalModuleToImportFrom(typeChecker, host, preferences, program.redirectTargetsMap, sourceFile, program.getSourceFiles(), moduleSymbol => { + const seenResolvedModules = createMap(); + + codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, program.getSourceFiles(), moduleSymbol => { // Perf -- ignore other modules if this is a request for details if (detailsEntryId && detailsEntryId.source && stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { return; @@ -1346,59 +1293,33 @@ namespace ts.Completions { symbolToOriginInfoMap[getSymbolId(resolvedModuleSymbol)] = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport: false }; } - for (const symbol of typeChecker.getExportsOfModule(moduleSymbol)) { - // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. - if (some(symbol.declarations, d => isExportSpecifier(d) && !!d.propertyName && isIdentifierANonContextualKeyword(d.name))) { + for (let symbol of typeChecker.getExportsOfModule(moduleSymbol)) { + // Don't add a completion for a re-export, only for the original. + // The actual import fix might end up coming from a re-export -- we don't compute that until getting completion details. + // This is just to avoid adding duplicate completion entries. + // + // If `symbol.parent !== ...`, this is an `export * from "foo"` re-export. Those don't create new symbols. + if (typeChecker.getMergedSymbol(symbol.parent!) !== resolvedModuleSymbol + || some(symbol.declarations, d => + // If `!!d.name.originalKeywordKind`, this is `export { _break as break };` -- skip this and prefer the keyword completion. + // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + isExportSpecifier(d) && (d.propertyName ? isIdentifierANonContextualKeyword(d.name) : !!d.parent.parent.moduleSpecifier))) { continue; } - // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. - const isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent!) !== resolvedModuleSymbol; - // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (isExportStarFromReExport || some(symbol.declarations, d => isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier)) { - // Walk the export chain back one module (step 1 or 2 in diagrammed example). - // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that. - const nearestExportSymbolId = getSymbolId(isExportStarFromReExport ? symbol : Debug.assertDefined(getNearestExportSymbol(symbol))); - const symbolHasBeenSeen = !!symbolToOriginInfoMap[nearestExportSymbolId] || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId.toString()); - if (!symbolHasBeenSeen) { - aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId.toString(), { alias: symbol, moduleSymbol }); - aliasesToAlreadyIncludedSymbols.set(getSymbolId(symbol).toString(), true); - } - else { - // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here - // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id. - addToSeen(aliasesToAlreadyIncludedSymbols, getSymbolId(symbol)); - } + + const isDefaultExport = symbol.escapedName === InternalSymbolName.Default; + if (isDefaultExport) { + symbol = getLocalSymbolForExportDefault(symbol) || symbol; } - else { - // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.delete(getSymbolId(symbol).toString()); - pushSymbol(symbol, moduleSymbol); + + const origin: SymbolOriginInfoExport = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport }; + if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToSortTextMap[getSymbolId(symbol)] = SortText.AutoImportSuggestions; + symbolToOriginInfoMap[getSymbolId(symbol)] = origin; } } }); - - // By this point, any potential duplicates that were actually duplicates have been - // removed, so the rest need to be added. (Step 4 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.forEach(({ alias, moduleSymbol }) => pushSymbol(alias, moduleSymbol)); - - function pushSymbol(symbol: Symbol, moduleSymbol: Symbol) { - const isDefaultExport = symbol.escapedName === InternalSymbolName.Default; - if (isDefaultExport) { - symbol = getLocalSymbolForExportDefault(symbol) || symbol; - } - const origin: SymbolOriginInfoExport = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport }; - if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { - symbols.push(symbol); - symbolToSortTextMap[getSymbolId(symbol)] = SortText.AutoImportSuggestions; - symbolToOriginInfoMap[getSymbolId(symbol)] = origin; - } - } - } - - function getNearestExportSymbol(fromSymbol: Symbol) { - return findAlias(typeChecker, fromSymbol, alias => { - return some(alias.declarations, d => isExportSpecifier(d) || !!d.localSymbol); - }); } /** @@ -2322,13 +2243,4 @@ namespace ts.Completions { function binaryExpressionMayBeOpenTag({ left }: BinaryExpression): boolean { return nodeIsMissing(left); } - - function findAlias(typeChecker: TypeChecker, symbol: Symbol, predicate: (symbol: Symbol) => boolean): Symbol | undefined { - let currentAlias: Symbol | undefined = symbol; - while (currentAlias.flags & SymbolFlags.Alias && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) { - if (predicate(currentAlias)) { - return currentAlias; - } - } - } } diff --git a/src/services/services.ts b/src/services/services.ts index 2f000bc0f2e..fab6f88b779 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1453,7 +1453,7 @@ namespace ts { function getCompletionEntrySymbol(fileName: string, position: number, name: string, source?: string): Symbol | undefined { synchronizeHostData(); - return Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name, source }, host); + return Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name, source }); } function getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined { diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index 58195b5cb3c..b287ebdb406 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -627,6 +627,30 @@ namespace ts.Completions.StringCompletions { } } + function findPackageJsons(directory: string, host: LanguageServiceHost): string[] { + const paths: string[] = []; + forEachAncestorDirectory(directory, ancestor => { + const currentConfigPath = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (!currentConfigPath) { + return true; // break out + } + paths.push(currentConfigPath); + }); + return paths; + } + + function findPackageJson(directory: string, host: LanguageServiceHost): string | undefined { + let packageJson: string | undefined; + forEachAncestorDirectory(directory, ancestor => { + if (ancestor === "node_modules") return true; + packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): ReadonlyArray { if (!host.readFile || !host.fileExists) return emptyArray; @@ -682,6 +706,31 @@ namespace ts.Completions.StringCompletions { const nodeModulesDependencyKeys: ReadonlyArray = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; + function tryGetDirectories(host: LanguageServiceHost, directoryName: string): string[] { + return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || []; + } + + function tryReadDirectory(host: LanguageServiceHost, path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray): ReadonlyArray { + return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray; + } + + function tryFileExists(host: LanguageServiceHost, path: string): boolean { + return tryIOAndConsumeErrors(host, host.fileExists, path); + } + + function tryDirectoryExists(host: LanguageServiceHost, path: string): boolean { + return tryAndIgnoreErrors(() => directoryProbablyExists(path, host)) || false; + } + + function tryIOAndConsumeErrors(host: LanguageServiceHost, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) { + return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args)); + } + + function tryAndIgnoreErrors(cb: () => T): T | undefined { + try { return cb(); } + catch { return undefined; } + } + function containsSlash(fragment: string) { return stringContains(fragment, directorySeparator); } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 98406c6879c..852d22106a2 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -2022,53 +2022,4 @@ namespace ts { // If even 2/5 places have a semicolon, the user probably wants semicolons return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve; } - - export function tryGetDirectories(host: LanguageServiceHost, directoryName: string): string[] { - return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || []; - } - - export function tryReadDirectory(host: LanguageServiceHost, path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray): ReadonlyArray { - return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray; - } - - export function tryFileExists(host: LanguageServiceHost, path: string): boolean { - return tryIOAndConsumeErrors(host, host.fileExists, path); - } - - export function tryDirectoryExists(host: LanguageServiceHost, path: string): boolean { - return tryAndIgnoreErrors(() => directoryProbablyExists(path, host)) || false; - } - - export function tryAndIgnoreErrors(cb: () => T): T | undefined { - try { return cb(); } - catch { return undefined; } - } - - export function tryIOAndConsumeErrors(host: LanguageServiceHost, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) { - return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args)); - } - - export function findPackageJsons(directory: string, host: LanguageServiceHost): string[] { - const paths: string[] = []; - forEachAncestorDirectory(directory, ancestor => { - const currentConfigPath = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); - if (!currentConfigPath) { - return true; // break out - } - paths.push(currentConfigPath); - }); - return paths; - } - - export function findPackageJson(directory: string, host: LanguageServiceHost): string | undefined { - let packageJson: string | undefined; - forEachAncestorDirectory(directory, ancestor => { - if (ancestor === "node_modules") return true; - packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); - if (packageJson) { - return true; // break out - } - }); - return packageJson; - } } diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesImplicit.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesImplicit.ts deleted file mode 100644 index 539a9cc8ff6..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesImplicit.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "react": "*" -//// } -////} - -//@Filename: /node_modules/@types/react/index.d.ts -////export declare var React: any; - -//@Filename: /node_modules/@types/react/package.json -////{ -//// "name": "@types/react" -////} - -//@Filename: /node_modules/@types/fake-react/index.d.ts -////export declare var ReactFake: any; - -//@Filename: /node_modules/@types/fake-react/package.json -////{ -//// "name": "@types/fake-react" -////} - -//@Filename: /src/index.ts -////const x = Re/**/ - -verify.completions({ - marker: test.marker(""), - isNewIdentifierLocation: true, - includes: { - name: "React", - hasAction: true, - source: "/node_modules/@types/react/index", - sortText: completion.SortText.AutoImportSuggestions - }, - excludes: "ReactFake", - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesOnly.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesOnly.ts deleted file mode 100644 index b0d2c01e3db..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_@typesOnly.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "devDependencies": { -//// "@types/react": "*" -//// } -////} - -//@Filename: /node_modules/@types/react/index.d.ts -////export declare var React: any; - -//@Filename: /node_modules/@types/react/package.json -////{ -//// "name": "@types/react" -////} - -//@Filename: /node_modules/@types/fake-react/index.d.ts -////export declare var ReactFake: any; - -//@Filename: /node_modules/@types/fake-react/package.json -////{ -//// "name": "@types/fake-react" -////} - -//@Filename: /src/index.ts -////const x = Re/**/ - -verify.completions({ - marker: test.marker(""), - isNewIdentifierLocation: true, - includes: { - name: "React", - hasAction: true, - source: "/node_modules/@types/react/index", - sortText: completion.SortText.AutoImportSuggestions - }, - excludes: "ReactFake", - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_ambient.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_ambient.ts deleted file mode 100644 index 3dcb9eb6690..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_ambient.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// } -////} - -//@Filename: /node_modules/@types/node/timers.d.ts -////declare module "timers" { -//// function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -////} - -//@Filename: /node_modules/@types/node/package.json -////{ -//// "name": "@types/node", -////} - -//@Filename: /src/index.ts -////setTimeo/**/ - -verify.completions({ - marker: test.marker(""), - exact: completion.globals, - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_direct.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_direct.ts deleted file mode 100644 index aa7845daed3..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_direct.ts +++ /dev/null @@ -1,46 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "react": "*" -//// } -////} - -//@Filename: /node_modules/react/index.d.ts -////export declare var React: any; - -//@Filename: /node_modules/react/package.json -////{ -//// "name": "react", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/fake-react/index.d.ts -////export declare var ReactFake: any; - -//@Filename: /node_modules/fake-react/package.json -////{ -//// "name": "fake-react", -//// "types": "./index.d.ts" -////} - -//@Filename: /src/index.ts -////const x = Re/**/ - -verify.completions({ - marker: test.marker(""), - isNewIdentifierLocation: true, - includes: { - name: "React", - hasAction: true, - source: "/node_modules/react/index", - sortText: completion.SortText.AutoImportSuggestions - }, - excludes: "ReactFake", - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_nested.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_nested.ts deleted file mode 100644 index e940c43e32c..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_nested.ts +++ /dev/null @@ -1,66 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "react": "*" -//// } -////} - -//@Filename: /node_modules/react/index.d.ts -////export declare var React: any; - -//@Filename: /node_modules/react/package.json -////{ -//// "name": "react", -//// "types": "./index.d.ts" -////} - -//@Filename: /dir/package.json -////{ -//// "dependencies": { -//// "redux": "*" -//// } -////} - -//@Filename: /dir/node_modules/redux/package.json -////{ -//// "name": "redux", -//// "types": "./index.d.ts" -////} - -//@Filename: /dir/node_modules/redux/index.d.ts -////export declare var Redux: any; - -//@Filename: /dir/index.ts -////const x = Re/**/ - -verify.completions({ - marker: test.marker(""), - isNewIdentifierLocation: true, - includes: { - name: "React", - hasAction: true, - source: "/node_modules/react/index", - sortText: completion.SortText.AutoImportSuggestions - }, - preferences: { - includeCompletionsForModuleExports: true - } -}); - -verify.completions({ - marker: test.marker(""), - isNewIdentifierLocation: true, - includes: { - name: "Redux", - hasAction: true, - source: "/dir/node_modules/redux/index", - sortText: completion.SortText.AutoImportSuggestions - }, - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport.ts deleted file mode 100644 index 8e17a3c3a44..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport.ts +++ /dev/null @@ -1,58 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "@emotion/core": "*" -//// } -////} - -//@Filename: /node_modules/@emotion/css/index.d.ts -////export declare const css: any; -////const css2: any; -////export { css2 }; - -//@Filename: /node_modules/@emotion/css/package.json -////{ -//// "name": "@emotion/css", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/@emotion/core/index.d.ts -////import { css2 } from "@emotion/css"; -////export { css } from "@emotion/css"; -////export { css2 }; - -//@Filename: /node_modules/@emotion/core/package.json -////{ -//// "name": "@emotion/core", -//// "types": "./index.d.ts" -////} - -//@Filename: /src/index.ts -////cs/**/ - -verify.completions({ - marker: test.marker(""), - includes: [ - completion.undefinedVarEntry, - { - name: "css", - source: "/node_modules/@emotion/core/index", - hasAction: true, - sortText: completion.SortText.AutoImportSuggestions - }, - { - name: "css2", - source: "/node_modules/@emotion/core/index", - hasAction: true, - sortText: completion.SortText.AutoImportSuggestions - }, - ...completion.statementKeywordsWithTypes - ], - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport2.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport2.ts deleted file mode 100644 index eb946ce17b4..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport2.ts +++ /dev/null @@ -1,58 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "b_": "*", -//// "_c": "*" -//// } -////} - -//@Filename: /node_modules/a/index.d.ts -////export const foo = 0; - -//@Filename: /node_modules/a/package.json -////{ -//// "name": "a", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/b_/index.d.ts -////export { foo } from "a"; - -//@Filename: /node_modules/b_/package.json -////{ -//// "name": "b_", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/_c/index.d.ts -////export { foo } from "b_"; - -//@Filename: /node_modules/_c/package.json -////{ -//// "name": "_c", -//// "types": "./index.d.ts" -////} - -//@Filename: /src/index.ts -////fo/**/ - -verify.completions({ - marker: test.marker(""), - includes: [ - completion.undefinedVarEntry, - { - name: "foo", - source: "/node_modules/b_/index", - hasAction: true, - sortText: completion.SortText.AutoImportSuggestions - }, - ...completion.statementKeywordsWithTypes - ], - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport3.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport3.ts deleted file mode 100644 index 8533461e0b8..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport3.ts +++ /dev/null @@ -1,48 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "b": "*", -//// } -////} - -//@Filename: /node_modules/a/index.d.ts -////export const foo = 0; - -//@Filename: /node_modules/a/package.json -////{ -//// "name": "a", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/b/index.d.ts -////export * from "a"; - -//@Filename: /node_modules/b/package.json -////{ -//// "name": "b", -//// "types": "./index.d.ts" -////} - -//@Filename: /src/index.ts -////fo/**/ - -verify.completions({ - marker: test.marker(""), - includes: [ - completion.undefinedVarEntry, - { - name: "foo", - source: "/node_modules/b/index", - hasAction: true, - sortText: completion.SortText.AutoImportSuggestions - }, - ...completion.statementKeywordsWithTypes - ], - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport4.ts b/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport4.ts deleted file mode 100644 index 83ac6526b25..00000000000 --- a/tests/cases/fourslash/completionsImport_filteredByPackageJson_reexport4.ts +++ /dev/null @@ -1,57 +0,0 @@ -/// - -//@noEmit: true - -//@Filename: /package.json -////{ -//// "dependencies": { -//// "c": "*", -//// } -////} - -//@Filename: /node_modules/a/index.d.ts -////export const foo = 0; - -//@Filename: /node_modules/a/package.json -////{ -//// "name": "a", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/b/index.d.ts -////export * from "a"; - -//@Filename: /node_modules/b/package.json -////{ -//// "name": "b", -//// "types": "./index.d.ts" -////} - -//@Filename: /node_modules/c/index.d.ts -////export * from "a"; - -//@Filename: /node_modules/c/package.json -////{ -//// "name": "c", -//// "types": "./index.d.ts" -////} - -//@Filename: /src/index.ts -////fo/**/ - -verify.completions({ - marker: test.marker(""), - includes: [ - completion.undefinedVarEntry, - { - name: "foo", - source: "/node_modules/c/index", - hasAction: true, - sortText: completion.SortText.AutoImportSuggestions - }, - ...completion.statementKeywordsWithTypes - ], - preferences: { - includeCompletionsForModuleExports: true - } -}); diff --git a/tests/cases/fourslash/completionsImport_ofAlias.ts b/tests/cases/fourslash/completionsImport_ofAlias.ts index 1319391eb0b..9a9cb4a2b18 100644 --- a/tests/cases/fourslash/completionsImport_ofAlias.ts +++ b/tests/cases/fourslash/completionsImport_ofAlias.ts @@ -16,9 +16,6 @@ // @Filename: /a_reexport_2.ts ////export * from "./a"; -// @Filename: /a_reexport_3.ts -////export { foo } from "./a_reexport"; - // @Filename: /b.ts ////fo/**/ @@ -27,13 +24,13 @@ verify.completions({ includes: [ completion.undefinedVarEntry, { - name: "foo", - source: "/a", - sourceDisplay: "./a", - text: "(alias) const foo: 0\nexport foo", - kind: "alias", - hasAction: true, - sortText: completion.SortText.AutoImportSuggestions + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "(alias) const foo: 0\nexport foo", + kind: "alias", + hasAction: true, + sortText: completion.SortText.AutoImportSuggestions }, ...completion.statementKeywordsWithTypes, ], diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts index acfddd587f7..f048f0d30d2 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts @@ -3,7 +3,7 @@ //// [|f1/*0*/('');|] // @Filename: package.json -//// { "dependencies": { "@scope/package-name": "latest" } } +//// { "dependencies": { "package-name": "latest" } } // @Filename: node_modules/@scope/package-name/bin/lib/index.d.ts //// export function f1(text: string): string; From 5a45d5aed8dc6b6c47d8ab23cdf161049d812afe Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 14:53:29 -0700 Subject: [PATCH 017/151] Reduce union and intersection targets when source is singleton type --- src/compiler/checker.ts | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 75b12ee37bb..1a2fc79534e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15500,15 +15500,10 @@ namespace ts { // of all their possible values. let matchingTypes: Type[] | undefined; for (const t of (source).types) { - if (typeIdenticalToSomeType(t, (target).types)) { - (matchingTypes || (matchingTypes = [])).push(t); - inferFromTypes(t, t); - } - else if (t.flags & (TypeFlags.NumberLiteral | TypeFlags.StringLiteral)) { - const b = getBaseTypeOfLiteralType(t); - if (typeIdenticalToSomeType(b, (target).types)) { - (matchingTypes || (matchingTypes = [])).push(t, b); - } + const matched = findMatchedType(t, target); + if (matched) { + (matchingTypes || (matchingTypes = [])).push(matched); + inferFromTypes(matched, matched); } } // Next, to improve the quality of inferences, reduce the source and target types by @@ -15519,6 +15514,14 @@ namespace ts { target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } + else if (target.flags & TypeFlags.Union && !(target.flags & TypeFlags.EnumLiteral) || target.flags & TypeFlags.Intersection) { + const matched = findMatchedType(source, target); + if (matched) { + inferFromTypes(matched, matched); + source = target.flags & TypeFlags.Union ? neverType : unknownType; + target = removeTypesFromUnionOrIntersection(target, [matched]); + } + } else if (target.flags & (TypeFlags.IndexedAccess | TypeFlags.Substitution)) { target = getActualTypeVariable(target); } @@ -15955,6 +15958,19 @@ namespace ts { return false; } + function findMatchedType(type: Type, target: UnionOrIntersectionType) { + if (typeIdenticalToSomeType(type, target.types)) { + return type; + } + if (type.flags & (TypeFlags.NumberLiteral | TypeFlags.StringLiteral) && target.flags & TypeFlags.Union) { + const base = getBaseTypeOfLiteralType(type); + if (typeIdenticalToSomeType(base, target.types)) { + return base; + } + } + return undefined; + } + /** * Return a new union or intersection type computed by removing a given set of types * from a given union or intersection type. From 652bb1277cd72946fde639479e816933dfd0cbd9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 14:54:27 -0700 Subject: [PATCH 018/151] Accept new baselines --- .../reference/unionAndIntersectionInference2.types | 2 +- .../reference/unionTypeInference.errors.txt | 13 +++++++++---- tests/baselines/reference/unionTypeInference.types | 6 +++--- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/baselines/reference/unionAndIntersectionInference2.types b/tests/baselines/reference/unionAndIntersectionInference2.types index a163b25ce28..031354506b7 100644 --- a/tests/baselines/reference/unionAndIntersectionInference2.types +++ b/tests/baselines/reference/unionAndIntersectionInference2.types @@ -20,7 +20,7 @@ var e1: number | string | boolean; >e1 : string | number | boolean f1(a1); // string ->f1(a1) : string +>f1(a1) : never >f1 : (x: string | T) => T >a1 : string diff --git a/tests/baselines/reference/unionTypeInference.errors.txt b/tests/baselines/reference/unionTypeInference.errors.txt index dfda0d57c2b..ec5c0e11f8d 100644 --- a/tests/baselines/reference/unionTypeInference.errors.txt +++ b/tests/baselines/reference/unionTypeInference.errors.txt @@ -1,7 +1,8 @@ -tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(9,15): error TS2345: Argument of type '2' is not assignable to parameter of type 'string | 1'. +tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(13,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'a3' must be of type 'number', but here has type 'string | number'. +tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(31,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'c2' must be of type 'string', but here has type 'never'. -==== tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts (1 errors) ==== +==== tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts (2 errors) ==== // Verify that inferences made *to* a type parameter in a union type are secondary // to inferences made directly to that type parameter @@ -11,12 +12,13 @@ tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference var a1: number; var a1 = f(1, 2); - ~ -!!! error TS2345: Argument of type '2' is not assignable to parameter of type 'string | 1'. var a2: number; var a2 = f(1, "hello"); var a3: number; var a3 = f(1, a1 || "hello"); + ~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a3' must be of type 'number', but here has type 'string | number'. +!!! related TS6203 tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts:12:5: 'a3' was also declared here. var a4: any; var a4 = f(undefined, "abc"); @@ -35,4 +37,7 @@ tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference var c1 = h(5); var c2: string; var c2 = h("abc"); + ~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'c2' must be of type 'string', but here has type 'never'. +!!! related TS6203 tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts:30:5: 'c2' was also declared here. \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeInference.types b/tests/baselines/reference/unionTypeInference.types index e712916c2ff..fc5b777ff5a 100644 --- a/tests/baselines/reference/unionTypeInference.types +++ b/tests/baselines/reference/unionTypeInference.types @@ -16,7 +16,7 @@ var a1: number; var a1 = f(1, 2); >a1 : number ->f(1, 2) : any +>f(1, 2) : 1 | 2 >f : (x: T, y: string | T) => T >1 : 1 >2 : 2 @@ -36,7 +36,7 @@ var a3: number; var a3 = f(1, a1 || "hello"); >a3 : number ->f(1, a1 || "hello") : number +>f(1, a1 || "hello") : number | "hello" >f : (x: T, y: string | T) => T >1 : 1 >a1 || "hello" : number | "hello" @@ -107,7 +107,7 @@ var c2: string; var c2 = h("abc"); >c2 : string ->h("abc") : "abc" +>h("abc") : never >h : (x: string | boolean | T) => T >"abc" : "abc" From 7d4259ba9fa4cfa039c36cc54aa5f1351aa36760 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 14:57:26 -0700 Subject: [PATCH 019/151] Update tests --- .../typeInference/unionTypeInference.ts | 61 +++++++++++-------- 1 file changed, 36 insertions(+), 25 deletions(-) diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts index 39def706622..14ce8e91fc7 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts @@ -1,31 +1,42 @@ -// Verify that inferences made *to* a type parameter in a union type are secondary -// to inferences made directly to that type parameter +// @strict: true -function f(x: T, y: string|T): T { - return x; -} +declare const b: boolean; +declare const s: string; +declare const sn: string | number; -var a1: number; -var a1 = f(1, 2); -var a2: number; -var a2 = f(1, "hello"); -var a3: number; -var a3 = f(1, a1 || "hello"); -var a4: any; -var a4 = f(undefined, "abc"); +declare function f1(x: T, y: string | T): T; -function g(value: [string, T]): T { - return value[1]; -} +const a1 = f1(1, 2); // 1 | 2 +const a2 = f1(1, "hello"); // 1 +const a3 = f1(1, sn); // number +const a4 = f1(undefined, "abc"); // undefined +const a5 = f1("foo", "bar"); // "foo" +const a6 = f1(true, false); // boolean +const a7 = f1("hello", 1); // Error -var b1: boolean; -var b1 = g(["string", true]); +declare function f2(value: [string, T]): T; -function h(x: string|boolean|T): T { - return typeof x === "string" || typeof x === "boolean" ? undefined : x; -} +var b1 = f2(["string", true]); // boolean -var c1: number; -var c1 = h(5); -var c2: string; -var c2 = h("abc"); +declare function f3(x: string | false | T): T; + +const c1 = f3(5); // 5 +const c2 = f3(sn); // number +const c3 = f3(true); // true +const c4 = f3(b); // true +const c5 = f3("abc"); // never + +declare function f4(x: string & T): T; + +var d1 = f4("abc"); +var d2 = f4(s); +var d3 = f4(42); // Error + +// Repros from #32434 + +declare function foo(x: T | Promise): void; +declare let x: false | Promise; +foo(x); + +declare function bar(x: T, y: string | T): T; +const y = bar(1, 2); From ae1add72104b6e3ca7a8e765af77f3bec9003ce6 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 15:02:20 -0700 Subject: [PATCH 020/151] Update tests --- .../typeRelationships/typeInference/unionTypeInference.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts index 14ce8e91fc7..ccedb753354 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts @@ -28,9 +28,9 @@ const c5 = f3("abc"); // never declare function f4(x: string & T): T; -var d1 = f4("abc"); -var d2 = f4(s); -var d3 = f4(42); // Error +const d1 = f4("abc"); +const d2 = f4(s); +const d3 = f4(42); // Error // Repros from #32434 From c4bad6443884ee7218f1b970784f2c03e23d52bb Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 15:03:15 -0700 Subject: [PATCH 021/151] Accept new baselines --- .../reference/unionTypeInference.errors.txt | 73 +++--- .../baselines/reference/unionTypeInference.js | 103 ++++----- .../reference/unionTypeInference.symbols | 194 ++++++++++------ .../reference/unionTypeInference.types | 210 +++++++++++------- 4 files changed, 342 insertions(+), 238 deletions(-) diff --git a/tests/baselines/reference/unionTypeInference.errors.txt b/tests/baselines/reference/unionTypeInference.errors.txt index ec5c0e11f8d..6993f4280a7 100644 --- a/tests/baselines/reference/unionTypeInference.errors.txt +++ b/tests/baselines/reference/unionTypeInference.errors.txt @@ -1,43 +1,50 @@ -tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(13,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'a3' must be of type 'number', but here has type 'string | number'. -tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(31,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'c2' must be of type 'string', but here has type 'never'. +tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(13,24): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. +tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(31,13): error TS2345: Argument of type '42' is not assignable to parameter of type 'never'. ==== tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts (2 errors) ==== - // Verify that inferences made *to* a type parameter in a union type are secondary - // to inferences made directly to that type parameter + declare const b: boolean; + declare const s: string; + declare const sn: string | number; - function f(x: T, y: string|T): T { - return x; - } + declare function f1(x: T, y: string | T): T; - var a1: number; - var a1 = f(1, 2); - var a2: number; - var a2 = f(1, "hello"); - var a3: number; - var a3 = f(1, a1 || "hello"); - ~~ -!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'a3' must be of type 'number', but here has type 'string | number'. -!!! related TS6203 tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts:12:5: 'a3' was also declared here. - var a4: any; - var a4 = f(undefined, "abc"); + const a1 = f1(1, 2); // 1 | 2 + const a2 = f1(1, "hello"); // 1 + const a3 = f1(1, sn); // number + const a4 = f1(undefined, "abc"); // undefined + const a5 = f1("foo", "bar"); // "foo" + const a6 = f1(true, false); // boolean + const a7 = f1("hello", 1); // Error + ~ +!!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. - function g(value: [string, T]): T { - return value[1]; - } + declare function f2(value: [string, T]): T; - var b1: boolean; - var b1 = g(["string", true]); + var b1 = f2(["string", true]); // boolean - function h(x: string|boolean|T): T { - return typeof x === "string" || typeof x === "boolean" ? undefined : x; - } + declare function f3(x: string | false | T): T; - var c1: number; - var c1 = h(5); - var c2: string; - var c2 = h("abc"); - ~~ -!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'c2' must be of type 'string', but here has type 'never'. -!!! related TS6203 tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts:30:5: 'c2' was also declared here. + const c1 = f3(5); // 5 + const c2 = f3(sn); // number + const c3 = f3(true); // true + const c4 = f3(b); // true + const c5 = f3("abc"); // never + + declare function f4(x: string & T): T; + + var d1 = f4("abc"); + var d2 = f4(s); + var d3 = f4(42); // Error + ~~ +!!! error TS2345: Argument of type '42' is not assignable to parameter of type 'never'. + + // Repros from #32434 + + declare function foo(x: T | Promise): void; + declare let x: false | Promise; + foo(x); + + declare function bar(x: T, y: string | T): T; + const y = bar(1, 2); \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeInference.js b/tests/baselines/reference/unionTypeInference.js index bdaa340f6ea..fb94e1910f1 100644 --- a/tests/baselines/reference/unionTypeInference.js +++ b/tests/baselines/reference/unionTypeInference.js @@ -1,60 +1,63 @@ //// [unionTypeInference.ts] -// Verify that inferences made *to* a type parameter in a union type are secondary -// to inferences made directly to that type parameter +declare const b: boolean; +declare const s: string; +declare const sn: string | number; -function f(x: T, y: string|T): T { - return x; -} +declare function f1(x: T, y: string | T): T; -var a1: number; -var a1 = f(1, 2); -var a2: number; -var a2 = f(1, "hello"); -var a3: number; -var a3 = f(1, a1 || "hello"); -var a4: any; -var a4 = f(undefined, "abc"); +const a1 = f1(1, 2); // 1 | 2 +const a2 = f1(1, "hello"); // 1 +const a3 = f1(1, sn); // number +const a4 = f1(undefined, "abc"); // undefined +const a5 = f1("foo", "bar"); // "foo" +const a6 = f1(true, false); // boolean +const a7 = f1("hello", 1); // Error -function g(value: [string, T]): T { - return value[1]; -} +declare function f2(value: [string, T]): T; -var b1: boolean; -var b1 = g(["string", true]); +var b1 = f2(["string", true]); // boolean -function h(x: string|boolean|T): T { - return typeof x === "string" || typeof x === "boolean" ? undefined : x; -} +declare function f3(x: string | false | T): T; -var c1: number; -var c1 = h(5); -var c2: string; -var c2 = h("abc"); +const c1 = f3(5); // 5 +const c2 = f3(sn); // number +const c3 = f3(true); // true +const c4 = f3(b); // true +const c5 = f3("abc"); // never + +declare function f4(x: string & T): T; + +var d1 = f4("abc"); +var d2 = f4(s); +var d3 = f4(42); // Error + +// Repros from #32434 + +declare function foo(x: T | Promise): void; +declare let x: false | Promise; +foo(x); + +declare function bar(x: T, y: string | T): T; +const y = bar(1, 2); //// [unionTypeInference.js] -// Verify that inferences made *to* a type parameter in a union type are secondary -// to inferences made directly to that type parameter -function f(x, y) { - return x; -} -var a1; -var a1 = f(1, 2); -var a2; -var a2 = f(1, "hello"); -var a3; -var a3 = f(1, a1 || "hello"); -var a4; -var a4 = f(undefined, "abc"); -function g(value) { - return value[1]; -} -var b1; -var b1 = g(["string", true]); -function h(x) { - return typeof x === "string" || typeof x === "boolean" ? undefined : x; -} -var c1; -var c1 = h(5); -var c2; -var c2 = h("abc"); +"use strict"; +var a1 = f1(1, 2); // 1 | 2 +var a2 = f1(1, "hello"); // 1 +var a3 = f1(1, sn); // number +var a4 = f1(undefined, "abc"); // undefined +var a5 = f1("foo", "bar"); // "foo" +var a6 = f1(true, false); // boolean +var a7 = f1("hello", 1); // Error +var b1 = f2(["string", true]); // boolean +var c1 = f3(5); // 5 +var c2 = f3(sn); // number +var c3 = f3(true); // true +var c4 = f3(b); // true +var c5 = f3("abc"); // never +var d1 = f4("abc"); +var d2 = f4(s); +var d3 = f4(42); // Error +foo(x); +var y = bar(1, 2); diff --git a/tests/baselines/reference/unionTypeInference.symbols b/tests/baselines/reference/unionTypeInference.symbols index 3388f279f4b..a34be279837 100644 --- a/tests/baselines/reference/unionTypeInference.symbols +++ b/tests/baselines/reference/unionTypeInference.symbols @@ -1,94 +1,140 @@ === tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts === -// Verify that inferences made *to* a type parameter in a union type are secondary -// to inferences made directly to that type parameter +declare const b: boolean; +>b : Symbol(b, Decl(unionTypeInference.ts, 0, 13)) -function f(x: T, y: string|T): T { ->f : Symbol(f, Decl(unionTypeInference.ts, 0, 0)) ->T : Symbol(T, Decl(unionTypeInference.ts, 3, 11)) ->x : Symbol(x, Decl(unionTypeInference.ts, 3, 14)) ->T : Symbol(T, Decl(unionTypeInference.ts, 3, 11)) ->y : Symbol(y, Decl(unionTypeInference.ts, 3, 19)) ->T : Symbol(T, Decl(unionTypeInference.ts, 3, 11)) ->T : Symbol(T, Decl(unionTypeInference.ts, 3, 11)) +declare const s: string; +>s : Symbol(s, Decl(unionTypeInference.ts, 1, 13)) - return x; ->x : Symbol(x, Decl(unionTypeInference.ts, 3, 14)) -} +declare const sn: string | number; +>sn : Symbol(sn, Decl(unionTypeInference.ts, 2, 13)) -var a1: number; ->a1 : Symbol(a1, Decl(unionTypeInference.ts, 7, 3), Decl(unionTypeInference.ts, 8, 3)) +declare function f1(x: T, y: string | T): T; +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) +>T : Symbol(T, Decl(unionTypeInference.ts, 4, 20)) +>x : Symbol(x, Decl(unionTypeInference.ts, 4, 23)) +>T : Symbol(T, Decl(unionTypeInference.ts, 4, 20)) +>y : Symbol(y, Decl(unionTypeInference.ts, 4, 28)) +>T : Symbol(T, Decl(unionTypeInference.ts, 4, 20)) +>T : Symbol(T, Decl(unionTypeInference.ts, 4, 20)) -var a1 = f(1, 2); ->a1 : Symbol(a1, Decl(unionTypeInference.ts, 7, 3), Decl(unionTypeInference.ts, 8, 3)) ->f : Symbol(f, Decl(unionTypeInference.ts, 0, 0)) +const a1 = f1(1, 2); // 1 | 2 +>a1 : Symbol(a1, Decl(unionTypeInference.ts, 6, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) -var a2: number; ->a2 : Symbol(a2, Decl(unionTypeInference.ts, 9, 3), Decl(unionTypeInference.ts, 10, 3)) +const a2 = f1(1, "hello"); // 1 +>a2 : Symbol(a2, Decl(unionTypeInference.ts, 7, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) -var a2 = f(1, "hello"); ->a2 : Symbol(a2, Decl(unionTypeInference.ts, 9, 3), Decl(unionTypeInference.ts, 10, 3)) ->f : Symbol(f, Decl(unionTypeInference.ts, 0, 0)) +const a3 = f1(1, sn); // number +>a3 : Symbol(a3, Decl(unionTypeInference.ts, 8, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) +>sn : Symbol(sn, Decl(unionTypeInference.ts, 2, 13)) -var a3: number; ->a3 : Symbol(a3, Decl(unionTypeInference.ts, 11, 3), Decl(unionTypeInference.ts, 12, 3)) - -var a3 = f(1, a1 || "hello"); ->a3 : Symbol(a3, Decl(unionTypeInference.ts, 11, 3), Decl(unionTypeInference.ts, 12, 3)) ->f : Symbol(f, Decl(unionTypeInference.ts, 0, 0)) ->a1 : Symbol(a1, Decl(unionTypeInference.ts, 7, 3), Decl(unionTypeInference.ts, 8, 3)) - -var a4: any; ->a4 : Symbol(a4, Decl(unionTypeInference.ts, 13, 3), Decl(unionTypeInference.ts, 14, 3)) - -var a4 = f(undefined, "abc"); ->a4 : Symbol(a4, Decl(unionTypeInference.ts, 13, 3), Decl(unionTypeInference.ts, 14, 3)) ->f : Symbol(f, Decl(unionTypeInference.ts, 0, 0)) +const a4 = f1(undefined, "abc"); // undefined +>a4 : Symbol(a4, Decl(unionTypeInference.ts, 9, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) >undefined : Symbol(undefined) -function g(value: [string, T]): T { ->g : Symbol(g, Decl(unionTypeInference.ts, 14, 29)) ->T : Symbol(T, Decl(unionTypeInference.ts, 16, 11)) ->value : Symbol(value, Decl(unionTypeInference.ts, 16, 14)) ->T : Symbol(T, Decl(unionTypeInference.ts, 16, 11)) ->T : Symbol(T, Decl(unionTypeInference.ts, 16, 11)) +const a5 = f1("foo", "bar"); // "foo" +>a5 : Symbol(a5, Decl(unionTypeInference.ts, 10, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) - return value[1]; ->value : Symbol(value, Decl(unionTypeInference.ts, 16, 14)) ->1 : Symbol(1) -} +const a6 = f1(true, false); // boolean +>a6 : Symbol(a6, Decl(unionTypeInference.ts, 11, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) -var b1: boolean; ->b1 : Symbol(b1, Decl(unionTypeInference.ts, 20, 3), Decl(unionTypeInference.ts, 21, 3)) +const a7 = f1("hello", 1); // Error +>a7 : Symbol(a7, Decl(unionTypeInference.ts, 12, 5)) +>f1 : Symbol(f1, Decl(unionTypeInference.ts, 2, 34)) -var b1 = g(["string", true]); ->b1 : Symbol(b1, Decl(unionTypeInference.ts, 20, 3), Decl(unionTypeInference.ts, 21, 3)) ->g : Symbol(g, Decl(unionTypeInference.ts, 14, 29)) +declare function f2(value: [string, T]): T; +>f2 : Symbol(f2, Decl(unionTypeInference.ts, 12, 26)) +>T : Symbol(T, Decl(unionTypeInference.ts, 14, 20)) +>value : Symbol(value, Decl(unionTypeInference.ts, 14, 23)) +>T : Symbol(T, Decl(unionTypeInference.ts, 14, 20)) +>T : Symbol(T, Decl(unionTypeInference.ts, 14, 20)) -function h(x: string|boolean|T): T { ->h : Symbol(h, Decl(unionTypeInference.ts, 21, 29)) ->T : Symbol(T, Decl(unionTypeInference.ts, 23, 11)) ->x : Symbol(x, Decl(unionTypeInference.ts, 23, 14)) ->T : Symbol(T, Decl(unionTypeInference.ts, 23, 11)) ->T : Symbol(T, Decl(unionTypeInference.ts, 23, 11)) +var b1 = f2(["string", true]); // boolean +>b1 : Symbol(b1, Decl(unionTypeInference.ts, 16, 3)) +>f2 : Symbol(f2, Decl(unionTypeInference.ts, 12, 26)) - return typeof x === "string" || typeof x === "boolean" ? undefined : x; ->x : Symbol(x, Decl(unionTypeInference.ts, 23, 14)) ->x : Symbol(x, Decl(unionTypeInference.ts, 23, 14)) ->undefined : Symbol(undefined) ->x : Symbol(x, Decl(unionTypeInference.ts, 23, 14)) -} +declare function f3(x: string | false | T): T; +>f3 : Symbol(f3, Decl(unionTypeInference.ts, 16, 30)) +>T : Symbol(T, Decl(unionTypeInference.ts, 18, 20)) +>x : Symbol(x, Decl(unionTypeInference.ts, 18, 23)) +>T : Symbol(T, Decl(unionTypeInference.ts, 18, 20)) +>T : Symbol(T, Decl(unionTypeInference.ts, 18, 20)) -var c1: number; ->c1 : Symbol(c1, Decl(unionTypeInference.ts, 27, 3), Decl(unionTypeInference.ts, 28, 3)) +const c1 = f3(5); // 5 +>c1 : Symbol(c1, Decl(unionTypeInference.ts, 20, 5)) +>f3 : Symbol(f3, Decl(unionTypeInference.ts, 16, 30)) -var c1 = h(5); ->c1 : Symbol(c1, Decl(unionTypeInference.ts, 27, 3), Decl(unionTypeInference.ts, 28, 3)) ->h : Symbol(h, Decl(unionTypeInference.ts, 21, 29)) +const c2 = f3(sn); // number +>c2 : Symbol(c2, Decl(unionTypeInference.ts, 21, 5)) +>f3 : Symbol(f3, Decl(unionTypeInference.ts, 16, 30)) +>sn : Symbol(sn, Decl(unionTypeInference.ts, 2, 13)) -var c2: string; ->c2 : Symbol(c2, Decl(unionTypeInference.ts, 29, 3), Decl(unionTypeInference.ts, 30, 3)) +const c3 = f3(true); // true +>c3 : Symbol(c3, Decl(unionTypeInference.ts, 22, 5)) +>f3 : Symbol(f3, Decl(unionTypeInference.ts, 16, 30)) -var c2 = h("abc"); ->c2 : Symbol(c2, Decl(unionTypeInference.ts, 29, 3), Decl(unionTypeInference.ts, 30, 3)) ->h : Symbol(h, Decl(unionTypeInference.ts, 21, 29)) +const c4 = f3(b); // true +>c4 : Symbol(c4, Decl(unionTypeInference.ts, 23, 5)) +>f3 : Symbol(f3, Decl(unionTypeInference.ts, 16, 30)) +>b : Symbol(b, Decl(unionTypeInference.ts, 0, 13)) + +const c5 = f3("abc"); // never +>c5 : Symbol(c5, Decl(unionTypeInference.ts, 24, 5)) +>f3 : Symbol(f3, Decl(unionTypeInference.ts, 16, 30)) + +declare function f4(x: string & T): T; +>f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) +>T : Symbol(T, Decl(unionTypeInference.ts, 26, 20)) +>x : Symbol(x, Decl(unionTypeInference.ts, 26, 23)) +>T : Symbol(T, Decl(unionTypeInference.ts, 26, 20)) +>T : Symbol(T, Decl(unionTypeInference.ts, 26, 20)) + +var d1 = f4("abc"); +>d1 : Symbol(d1, Decl(unionTypeInference.ts, 28, 3)) +>f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) + +var d2 = f4(s); +>d2 : Symbol(d2, Decl(unionTypeInference.ts, 29, 3)) +>f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) +>s : Symbol(s, Decl(unionTypeInference.ts, 1, 13)) + +var d3 = f4(42); // Error +>d3 : Symbol(d3, Decl(unionTypeInference.ts, 30, 3)) +>f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) + +// Repros from #32434 + +declare function foo(x: T | Promise): void; +>foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 16)) +>T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) +>x : Symbol(x, Decl(unionTypeInference.ts, 34, 24)) +>T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) + +declare let x: false | Promise; +>x : Symbol(x, Decl(unionTypeInference.ts, 35, 11)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) + +foo(x); +>foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 16)) +>x : Symbol(x, Decl(unionTypeInference.ts, 35, 11)) + +declare function bar(x: T, y: string | T): T; +>bar : Symbol(bar, Decl(unionTypeInference.ts, 36, 7)) +>T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) +>x : Symbol(x, Decl(unionTypeInference.ts, 38, 24)) +>T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) +>y : Symbol(y, Decl(unionTypeInference.ts, 38, 29)) +>T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) +>T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) + +const y = bar(1, 2); +>y : Symbol(y, Decl(unionTypeInference.ts, 39, 5)) +>bar : Symbol(bar, Decl(unionTypeInference.ts, 36, 7)) diff --git a/tests/baselines/reference/unionTypeInference.types b/tests/baselines/reference/unionTypeInference.types index fc5b777ff5a..836c298bdbc 100644 --- a/tests/baselines/reference/unionTypeInference.types +++ b/tests/baselines/reference/unionTypeInference.types @@ -1,113 +1,161 @@ === tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts === -// Verify that inferences made *to* a type parameter in a union type are secondary -// to inferences made directly to that type parameter +declare const b: boolean; +>b : boolean -function f(x: T, y: string|T): T { ->f : (x: T, y: string | T) => T +declare const s: string; +>s : string + +declare const sn: string | number; +>sn : string | number + +declare function f1(x: T, y: string | T): T; +>f1 : (x: T, y: string | T) => T >x : T >y : string | T - return x; ->x : T -} - -var a1: number; ->a1 : number - -var a1 = f(1, 2); ->a1 : number ->f(1, 2) : 1 | 2 ->f : (x: T, y: string | T) => T +const a1 = f1(1, 2); // 1 | 2 +>a1 : 1 | 2 +>f1(1, 2) : 1 | 2 +>f1 : (x: T, y: string | T) => T >1 : 1 >2 : 2 -var a2: number; ->a2 : number - -var a2 = f(1, "hello"); ->a2 : number ->f(1, "hello") : 1 ->f : (x: T, y: string | T) => T +const a2 = f1(1, "hello"); // 1 +>a2 : 1 +>f1(1, "hello") : 1 +>f1 : (x: T, y: string | T) => T >1 : 1 >"hello" : "hello" -var a3: number; +const a3 = f1(1, sn); // number >a3 : number - -var a3 = f(1, a1 || "hello"); ->a3 : number ->f(1, a1 || "hello") : number | "hello" ->f : (x: T, y: string | T) => T +>f1(1, sn) : number +>f1 : (x: T, y: string | T) => T >1 : 1 ->a1 || "hello" : number | "hello" ->a1 : number ->"hello" : "hello" +>sn : string | number -var a4: any; ->a4 : any - -var a4 = f(undefined, "abc"); ->a4 : any ->f(undefined, "abc") : any ->f : (x: T, y: string | T) => T +const a4 = f1(undefined, "abc"); // undefined +>a4 : undefined +>f1(undefined, "abc") : undefined +>f1 : (x: T, y: string | T) => T >undefined : undefined >"abc" : "abc" -function g(value: [string, T]): T { ->g : (value: [string, T]) => T ->value : [string, T] +const a5 = f1("foo", "bar"); // "foo" +>a5 : "foo" +>f1("foo", "bar") : "foo" +>f1 : (x: T, y: string | T) => T +>"foo" : "foo" +>"bar" : "bar" - return value[1]; ->value[1] : T ->value : [string, T] +const a6 = f1(true, false); // boolean +>a6 : boolean +>f1(true, false) : boolean +>f1 : (x: T, y: string | T) => T +>true : true +>false : false + +const a7 = f1("hello", 1); // Error +>a7 : any +>f1("hello", 1) : any +>f1 : (x: T, y: string | T) => T +>"hello" : "hello" >1 : 1 -} -var b1: boolean; ->b1 : boolean +declare function f2(value: [string, T]): T; +>f2 : (value: [string, T]) => T +>value : [string, T] -var b1 = g(["string", true]); +var b1 = f2(["string", true]); // boolean >b1 : boolean ->g(["string", true]) : boolean ->g : (value: [string, T]) => T +>f2(["string", true]) : boolean +>f2 : (value: [string, T]) => T >["string", true] : [string, true] >"string" : "string" >true : true -function h(x: string|boolean|T): T { ->h : (x: string | boolean | T) => T ->x : string | boolean | T +declare function f3(x: string | false | T): T; +>f3 : (x: string | false | T) => T +>x : string | false | T +>false : false - return typeof x === "string" || typeof x === "boolean" ? undefined : x; ->typeof x === "string" || typeof x === "boolean" ? undefined : x : T ->typeof x === "string" || typeof x === "boolean" : boolean ->typeof x === "string" : boolean ->typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" ->x : string | boolean | T ->"string" : "string" ->typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" ->x : boolean | T ->"boolean" : "boolean" ->undefined : undefined ->x : T -} - -var c1: number; ->c1 : number - -var c1 = h(5); ->c1 : number ->h(5) : 5 ->h : (x: string | boolean | T) => T +const c1 = f3(5); // 5 +>c1 : 5 +>f3(5) : 5 +>f3 : (x: string | false | T) => T >5 : 5 -var c2: string; ->c2 : string +const c2 = f3(sn); // number +>c2 : number +>f3(sn) : number +>f3 : (x: string | false | T) => T +>sn : string | number -var c2 = h("abc"); ->c2 : string ->h("abc") : never ->h : (x: string | boolean | T) => T +const c3 = f3(true); // true +>c3 : true +>f3(true) : true +>f3 : (x: string | false | T) => T +>true : true + +const c4 = f3(b); // true +>c4 : true +>f3(b) : true +>f3 : (x: string | false | T) => T +>b : boolean + +const c5 = f3("abc"); // never +>c5 : never +>f3("abc") : never +>f3 : (x: string | false | T) => T >"abc" : "abc" +declare function f4(x: string & T): T; +>f4 : (x: string & T) => T +>x : string & T + +var d1 = f4("abc"); +>d1 : string +>f4("abc") : "abc" +>f4 : (x: string & T) => T +>"abc" : "abc" + +var d2 = f4(s); +>d2 : unknown +>f4(s) : unknown +>f4 : (x: string & T) => T +>s : string + +var d3 = f4(42); // Error +>d3 : any +>f4(42) : any +>f4 : (x: string & T) => T +>42 : 42 + +// Repros from #32434 + +declare function foo(x: T | Promise): void; +>foo : (x: T | Promise) => void +>x : T | Promise + +declare let x: false | Promise; +>x : false | Promise +>false : false +>true : true + +foo(x); +>foo(x) : void +>foo : (x: T | Promise) => void +>x : false | Promise + +declare function bar(x: T, y: string | T): T; +>bar : (x: T, y: string | T) => T +>x : T +>y : string | T + +const y = bar(1, 2); +>y : 1 | 2 +>bar(1, 2) : 1 | 2 +>bar : (x: T, y: string | T) => T +>1 : 1 +>2 : 2 + From de837ed51f8f6f329cee97932bf3a8e7ea4cc46e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 15:07:36 -0700 Subject: [PATCH 022/151] Accept new baselines --- .../reference/unionTypeInference.errors.txt | 10 +++++----- tests/baselines/reference/unionTypeInference.js | 6 +++--- .../reference/unionTypeInference.symbols | 16 ++++++++-------- .../baselines/reference/unionTypeInference.types | 8 ++++---- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/tests/baselines/reference/unionTypeInference.errors.txt b/tests/baselines/reference/unionTypeInference.errors.txt index 6993f4280a7..2fe480d0a07 100644 --- a/tests/baselines/reference/unionTypeInference.errors.txt +++ b/tests/baselines/reference/unionTypeInference.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(13,24): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. -tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(31,13): error TS2345: Argument of type '42' is not assignable to parameter of type 'never'. +tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts(31,15): error TS2345: Argument of type '42' is not assignable to parameter of type 'never'. ==== tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts (2 errors) ==== @@ -33,10 +33,10 @@ tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference declare function f4(x: string & T): T; - var d1 = f4("abc"); - var d2 = f4(s); - var d3 = f4(42); // Error - ~~ + const d1 = f4("abc"); + const d2 = f4(s); + const d3 = f4(42); // Error + ~~ !!! error TS2345: Argument of type '42' is not assignable to parameter of type 'never'. // Repros from #32434 diff --git a/tests/baselines/reference/unionTypeInference.js b/tests/baselines/reference/unionTypeInference.js index fb94e1910f1..868140e83a0 100644 --- a/tests/baselines/reference/unionTypeInference.js +++ b/tests/baselines/reference/unionTypeInference.js @@ -27,9 +27,9 @@ const c5 = f3("abc"); // never declare function f4(x: string & T): T; -var d1 = f4("abc"); -var d2 = f4(s); -var d3 = f4(42); // Error +const d1 = f4("abc"); +const d2 = f4(s); +const d3 = f4(42); // Error // Repros from #32434 diff --git a/tests/baselines/reference/unionTypeInference.symbols b/tests/baselines/reference/unionTypeInference.symbols index a34be279837..52b8809dee6 100644 --- a/tests/baselines/reference/unionTypeInference.symbols +++ b/tests/baselines/reference/unionTypeInference.symbols @@ -94,23 +94,23 @@ declare function f4(x: string & T): T; >T : Symbol(T, Decl(unionTypeInference.ts, 26, 20)) >T : Symbol(T, Decl(unionTypeInference.ts, 26, 20)) -var d1 = f4("abc"); ->d1 : Symbol(d1, Decl(unionTypeInference.ts, 28, 3)) +const d1 = f4("abc"); +>d1 : Symbol(d1, Decl(unionTypeInference.ts, 28, 5)) >f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) -var d2 = f4(s); ->d2 : Symbol(d2, Decl(unionTypeInference.ts, 29, 3)) +const d2 = f4(s); +>d2 : Symbol(d2, Decl(unionTypeInference.ts, 29, 5)) >f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) >s : Symbol(s, Decl(unionTypeInference.ts, 1, 13)) -var d3 = f4(42); // Error ->d3 : Symbol(d3, Decl(unionTypeInference.ts, 30, 3)) +const d3 = f4(42); // Error +>d3 : Symbol(d3, Decl(unionTypeInference.ts, 30, 5)) >f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) // Repros from #32434 declare function foo(x: T | Promise): void; ->foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 16)) +>foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 18)) >T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) >x : Symbol(x, Decl(unionTypeInference.ts, 34, 24)) >T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) @@ -122,7 +122,7 @@ declare let x: false | Promise; >Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) foo(x); ->foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 16)) +>foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 18)) >x : Symbol(x, Decl(unionTypeInference.ts, 35, 11)) declare function bar(x: T, y: string | T): T; diff --git a/tests/baselines/reference/unionTypeInference.types b/tests/baselines/reference/unionTypeInference.types index 836c298bdbc..e6d47fa4bda 100644 --- a/tests/baselines/reference/unionTypeInference.types +++ b/tests/baselines/reference/unionTypeInference.types @@ -113,19 +113,19 @@ declare function f4(x: string & T): T; >f4 : (x: string & T) => T >x : string & T -var d1 = f4("abc"); ->d1 : string +const d1 = f4("abc"); +>d1 : "abc" >f4("abc") : "abc" >f4 : (x: string & T) => T >"abc" : "abc" -var d2 = f4(s); +const d2 = f4(s); >d2 : unknown >f4(s) : unknown >f4 : (x: string & T) => T >s : string -var d3 = f4(42); // Error +const d3 = f4(42); // Error >d3 : any >f4(42) : any >f4 : (x: string & T) => T From 69ec5e03663bc2ad25ae11b20baf0eb767ce3d5d Mon Sep 17 00:00:00 2001 From: csigs Date: Wed, 17 Jul 2019 22:10:20 +0000 Subject: [PATCH 023/151] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8d7a0a4acbd..5ba07d067e1 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,4 +1,4 @@ - + @@ -3300,7 +3300,7 @@ - + @@ -4122,7 +4122,7 @@ - + From c6b77fa5dfe9a396c24035ed77a947c81a1ba42f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 15:15:56 -0700 Subject: [PATCH 024/151] Fix lint error --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1a2fc79534e..81c2a9590ba 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15773,7 +15773,7 @@ namespace ts { // type variable. If there is more than one naked type variable, give lower priority to // the inferences as they are less specific. if (typeVariableCount > 0) { - const unmatched = flatMap(sources, (s, i) => matched![i] ? undefined : s); + const unmatched = flatMap(sources, (s, i) => matched[i] ? undefined : s); if (unmatched.length) { const s = getUnionType(unmatched); const savePriority = priority; From 7f071d2a1bda299cf3ac4eacb8abae951a095534 Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Wed, 17 Jul 2019 18:21:53 -0400 Subject: [PATCH 025/151] Set the ScriptTarget of ESNext to be 99 so it doesn't change between releases --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 439dfb5f98e..6d46d36d167 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4808,7 +4808,7 @@ namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, - ESNext = 8, + ESNext = 99, JSON = 100, Latest = ESNext, } From a24e4b0d2ca34b6ad12aae9218ea4e2f9ddd32f4 Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Wed, 17 Jul 2019 18:24:35 -0400 Subject: [PATCH 026/151] Undo accidental push to master --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 6d46d36d167..439dfb5f98e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4808,7 +4808,7 @@ namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, - ESNext = 99, + ESNext = 8, JSON = 100, Latest = ESNext, } From 5f6cdf17ea0441f42190610254c9d7f0c024459e Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Wed, 17 Jul 2019 18:27:29 -0400 Subject: [PATCH 027/151] Set the ScriptTarget of ESNext to be 99 so it doesn't change between releases --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 439dfb5f98e..6d46d36d167 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4808,7 +4808,7 @@ namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, - ESNext = 8, + ESNext = 99, JSON = 100, Latest = ESNext, } From 8f020559fbde9d0c8252a3fde5dc4f2890461fb0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jul 2019 18:49:56 -0700 Subject: [PATCH 028/151] Treat Array and ReadonlyArray as synonymous in inference --- src/compiler/checker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 81c2a9590ba..f044ee8e375 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15587,7 +15587,8 @@ namespace ts { } } } - if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { + if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( + (source).target === (target).target || isArrayType(source) && isArrayType(target))) { // If source and target are references to the same generic type, infer from type arguments inferFromTypeArguments((source).typeArguments || emptyArray, (target).typeArguments || emptyArray, getVariances((source).target)); } From 282e72419b2421c2d3b86d18a15256602df530a1 Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Wed, 17 Jul 2019 22:56:28 -0400 Subject: [PATCH 029/151] Set the ModuleKind value for ESNext to be 99 so it doesn't change between releases (and yet another module system?!) --- src/compiler/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 6d46d36d167..67c85147aed 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4760,7 +4760,7 @@ namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6 + ESNext = 99 } export const enum JsxEmit { From 0c4422e47203cc3a5b3680aac443ab031c03c1fb Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Thu, 18 Jul 2019 11:08:39 -0400 Subject: [PATCH 030/151] Adds baseline updates --- tests/baselines/reference/api/tsserverlibrary.d.ts | 6 +++--- tests/baselines/reference/api/typescript.d.ts | 6 +++--- .../sample1/initial-Build/when-target-option-changes.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 1810cb020e3..c2bad61505b 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2600,7 +2600,7 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6 + ESNext = 99 } enum JsxEmit { None = 0, @@ -2640,9 +2640,9 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, - ESNext = 8, + ESNext = 99, JSON = 100, - Latest = 8 + Latest = 99 } enum LanguageVariant { Standard = 0, diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index f74b4b14683..7a2559bbc22 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2600,7 +2600,7 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6 + ESNext = 99 } enum JsxEmit { None = 0, @@ -2640,9 +2640,9 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, - ESNext = 8, + ESNext = 99, JSON = 100, - Latest = 8 + Latest = 99 } enum LanguageVariant { Standard = 0, diff --git a/tests/baselines/reference/tsbuild/sample1/initial-Build/when-target-option-changes.js b/tests/baselines/reference/tsbuild/sample1/initial-Build/when-target-option-changes.js index 895ac5e4bc5..c31d39c0647 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-Build/when-target-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-Build/when-target-option-changes.js @@ -70,7 +70,7 @@ export function multiply(a, b) { return a * b; } "incremental": true, "listFiles": true, "listEmittedFiles": true, - "target": 8, + "target": 99, "configFilePath": "./tsconfig.json" }, "referencedMap": {}, From c30ba7884c76a9e94772c0c89604cb6cbfaced99 Mon Sep 17 00:00:00 2001 From: Jake Boone Date: Thu, 18 Jul 2019 12:38:14 -0700 Subject: [PATCH 031/151] Fix capitalization in parseInt description --- src/lib/es5.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 0d1481dd7d2..2594344decc 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -12,7 +12,7 @@ declare var Infinity: number; declare function eval(x: string): any; /** - * Converts A string to an integer. + * Converts a string to an integer. * @param s A string to convert into a number. * @param radix A value between 2 and 36 that specifies the base of the number in numString. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. From 90afd6d620f30bc47e862970a931ca0e207e6b28 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Fri, 19 Jul 2019 09:01:05 -0700 Subject: [PATCH 032/151] Update user baselines (#32483) --- .../baselines/reference/docker/azure-sdk.log | 58 ++++++------------- .../reference/docker/office-ui-fabric.log | 16 ++--- .../reference/user/adonis-framework.log | 2 +- .../user/chrome-devtools-frontend.log | 3 +- tests/baselines/reference/user/lodash.log | 2 - tests/baselines/reference/user/npmlog.log | 6 +- 6 files changed, 33 insertions(+), 54 deletions(-) diff --git a/tests/baselines/reference/docker/azure-sdk.log b/tests/baselines/reference/docker/azure-sdk.log index a1e33524e6e..a75af93aee1 100644 --- a/tests/baselines/reference/docker/azure-sdk.log +++ b/tests/baselines/reference/docker/azure-sdk.log @@ -5,16 +5,11 @@ Rush Multi-Project Build Tool 5.10.1 - https://rushjs.io Starting "rush rebuild" Executing a maximum of 1 simultaneous processes... [@azure/cosmos] started -npm ERR! code ELIFECYCLE -npm ERR! errno 2 -npm ERR! @azure/cosmos@X.X.X compile: `echo Using TypeScript && tsc --version && tsc -p tsconfig.prod.json --pretty` -npm ERR! Exit status 2 -npm ERR! -npm ERR! Failed at the @azure/cosmos@X.X.X compile script. -npm ERR! This is probably not a problem with npm. There is likely additional logging output above. -npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-15T13_35_10_789Z-debug.log +XX of XX: [@azure/cosmos] completed successfully in ? seconds +[@azure/event-processor-host] started +XX of XX: [@azure/event-processor-host] completed successfully in ? seconds [@azure/service-bus] started +Warning: You have changed the public API signature for this project. Updating review/service-bus.api.md [@azure/storage-blob] started XX of XX: [@azure/storage-blob] completed successfully in ? seconds [@azure/storage-file] started @@ -23,6 +18,8 @@ XX of XX: [@azure/storage-file] completed successfully in ? seconds XX of XX: [@azure/storage-queue] completed successfully in ? seconds [@azure/template] started XX of XX: [@azure/template] completed successfully in ? seconds +[testhub] started +XX of XX: [testhub] completed successfully in ? seconds [@azure/abort-controller] started XX of XX: [@azure/abort-controller] completed successfully in ? seconds [@azure/core-asynciterator-polyfill] started @@ -38,7 +35,7 @@ npm ERR! npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:tsc script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-15T13_36_24_862Z-debug.log +npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_496Z-debug.log ERROR: "build:tsc" exited with 2. npm ERR! code ELIFECYCLE npm ERR! errno 1 @@ -48,20 +45,17 @@ npm ERR! npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:lib script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-15T13_36_24_938Z-debug.log +npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_533Z-debug.log ERROR: "build:lib" exited with 1. [@azure/core-paging] started XX of XX: [@azure/core-paging] completed successfully in ? seconds -[@azure/event-processor-host] started -XX of XX: [@azure/event-processor-host] completed successfully in ? seconds -[testhub] started -XX of XX: [testhub] completed successfully in ? seconds -SUCCESS (10) +SUCCESS (11) ================================ @azure/abort-controller (? seconds) @azure/core-asynciterator-polyfill (? seconds) @azure/core-auth (? seconds) @azure/core-paging (? seconds) +@azure/cosmos (? seconds) @azure/event-processor-host (? seconds) @azure/storage-blob (? seconds) @azure/storage-file (? seconds) @@ -69,6 +63,11 @@ SUCCESS (10) @azure/template (? seconds) testhub (? seconds) ================================ +SUCCESS WITH WARNINGS (1) +================================ +@azure/service-bus (? seconds) +Warning: You have changed the public API signature for this project. Updating review/service-bus.api.md +================================ BLOCKED (7) ================================ @azure/core-amqp @@ -79,7 +78,7 @@ BLOCKED (7) @azure/keyvault-keys @azure/keyvault-secrets ================================ -FAILURE (3) +FAILURE (1) ================================ @azure/core-http (? seconds) npm ERR! code ELIFECYCLE @@ -90,7 +89,7 @@ npm ERR! npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:tsc script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-15T13_36_24_862Z-debug.log +npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_496Z-debug.log ERROR: "build:tsc" exited with 2. npm ERR! code ELIFECYCLE npm ERR! errno 1 @@ -100,24 +99,8 @@ npm ERR! npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:lib script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-15T13_36_24_938Z-debug.log +npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_533Z-debug.log ERROR: "build:lib" exited with 1. -@azure/cosmos ( ? seconds) -npm ERR! code ELIFECYCLE -npm ERR! errno 2 -npm ERR! @azure/cosmos@X.X.X compile: `echo Using TypeScript && tsc --version && tsc -p tsconfig.prod.json --pretty` -npm ERR! Exit status 2 -npm ERR! -npm ERR! Failed at the @azure/cosmos@X.X.X compile script. -npm ERR! This is probably not a problem with npm. There is likely additional logging output above. -npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-15T13_35_10_789Z-debug.log -@azure/service-bus ( ? seconds) ->>> @azure/service-bus -tsc -p . && rollup -c 2>&1 && npm run extract-api -error TS2318: Cannot find global type 'AsyncGenerator'. -src/receiver.ts(193,32): error TS2739: Type '{}' is missing the following properties from type 'AsyncIterableIterator': [Symbol.asyncIterator], next -src/receiver.ts(742,32): error TS2322: Type '{}' is not assignable to type 'AsyncIterableIterator'. ================================ Error: Project(s) failed to build rush rebuild - Errors! ( ? seconds) @@ -126,8 +109,7 @@ rush rebuild - Errors! ( ? seconds) Standard error: Your version of Node.js (X.X.X) has not been tested with this release of Rush. The Rush team will not accept issue reports for it. Please consider upgrading Rush or downgrading Node.js. -XX of XX: [@azure/cosmos] failed to build! -XX of XX: [@azure/service-bus] failed to build! +XX of XX: [@azure/service-bus] completed with warnings in ? seconds XX of XX: [@azure/core-http] failed to build! XX of XX: [@azure/core-arm] blocked by [@azure/core-http]! XX of XX: [@azure/identity] blocked by [@azure/core-http]! @@ -137,5 +119,3 @@ XX of XX: [@azure/keyvault-certificates] blocked by [@azure/core-http]! XX of XX: [@azure/keyvault-keys] blocked by [@azure/core-http]! XX of XX: [@azure/keyvault-secrets] blocked by [@azure/core-http]! [@azure/core-http] Returned error code: 1 -[@azure/cosmos] Returned error code: 2 -[@azure/service-bus] Returned error code: 2 diff --git a/tests/baselines/reference/docker/office-ui-fabric.log b/tests/baselines/reference/docker/office-ui-fabric.log index c3a55fc3f6b..888e20cac4b 100644 --- a/tests/baselines/reference/docker/office-ui-fabric.log +++ b/tests/baselines/reference/docker/office-ui-fabric.log @@ -12,11 +12,11 @@ XX of XX: [@uifabric/tslint-rules] completed successfully in ? seconds ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. PASS src/__tests__/codepenTransform.test.ts codepen transform - ✓ handles examples with function components (225ms) + ✓ handles examples with function components (256ms) ✓ handles examples with class components (38ms) - ✓ handles examples importing exampleData (115ms) - ✓ handles examples importing TestImages (45ms) - ✓ handles examples importing PeopleExampleData (288ms) + ✓ handles examples importing exampleData (125ms) + ✓ handles examples importing TestImages (33ms) + ✓ handles examples importing PeopleExampleData (270ms) Test Suites: 1 passed, 1 total Tests: 5 passed, 5 total Snapshots: 4 passed, 4 total @@ -246,11 +246,11 @@ SUCCESS WITH WARNINGS (5) ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. PASS src/__tests__/codepenTransform.test.ts codepen transform - ✓ handles examples with function components (225ms) + ✓ handles examples with function components (256ms) ✓ handles examples with class components (38ms) - ✓ handles examples importing exampleData (115ms) - ✓ handles examples importing TestImages (45ms) - ✓ handles examples importing PeopleExampleData (288ms) + ✓ handles examples importing exampleData (125ms) + ✓ handles examples importing TestImages (33ms) + ✓ handles examples importing PeopleExampleData (270ms) Test Suites: 1 passed, 1 total Tests: 5 passed, 5 total Snapshots: 4 passed, 4 total diff --git a/tests/baselines/reference/user/adonis-framework.log b/tests/baselines/reference/user/adonis-framework.log index e3b19b5de04..6243a7a15db 100644 --- a/tests/baselines/reference/user/adonis-framework.log +++ b/tests/baselines/reference/user/adonis-framework.log @@ -30,7 +30,7 @@ node_modules/adonis-framework/src/Encryption/index.js(87,15): error TS2304: Cann node_modules/adonis-framework/src/Encryption/index.js(101,21): error TS2769: No overload matches this call. Overload 1 of 4, '(data: Binary, input_encoding: undefined, output_encoding: Utf8AsciiBinaryEncoding): string', gave the following error. Argument of type '"base64"' is not assignable to parameter of type 'undefined'. - Overload 2 of 4, '(data: string, input_encoding: "binary" | "base64" | "hex" | undefined, output_encoding: Utf8AsciiBinaryEncoding): string', gave the following error. + Overload 2 of 4, '(data: string, input_encoding: "base64" | "binary" | "hex" | undefined, output_encoding: Utf8AsciiBinaryEncoding): string', gave the following error. Argument of type 'string' is not assignable to parameter of type 'Utf8AsciiBinaryEncoding'. node_modules/adonis-framework/src/Encryption/index.js(114,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Encryption/index.js(119,23): error TS2554: Expected 2 arguments, but got 1. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 3f4fa8d5b95..2d4e456d759 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -6501,7 +6501,8 @@ node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn_loo node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn_loose.js(258,55): error TS2339: Property 'end' does not exist on type 'true'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn_loose.js(1365,5): error TS2339: Property 'next' does not exist on type 'LooseParser'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn_loose.js(1366,12): error TS2339: Property 'parseTopLevel' does not exist on type 'LooseParser'. -node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(26,11): error TS2403: Subsequent variable declarations must have the same type. Variable 'page' must be of type 'any', but here has type 'HARPage'. +node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(16,32): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(16,52): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(46,5): error TS2322: Type 'Date' is not assignable to type 'number'. node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(320,70): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(321,35): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index 954077ce729..1c358238f8d 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -382,8 +382,6 @@ node_modules/lodash/nthArg.js(28,26): error TS2345: Argument of type 'number | u node_modules/lodash/omit.js(48,32): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean'. node_modules/lodash/orderBy.js(18,10): error TS1003: Identifier expected. node_modules/lodash/orderBy.js(18,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. -node_modules/lodash/org.js(8,22): error TS2307: Cannot find module 'moment'. -node_modules/lodash/org.js(9,19): error TS2307: Cannot find module 'ncp'. node_modules/lodash/parseInt.js(24,10): error TS1003: Identifier expected. node_modules/lodash/parseInt.js(24,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. node_modules/lodash/partial.js(48,9): error TS2339: Property 'placeholder' does not exist on type 'Function'. diff --git a/tests/baselines/reference/user/npmlog.log b/tests/baselines/reference/user/npmlog.log index 1e6284674e3..6b6e315d996 100644 --- a/tests/baselines/reference/user/npmlog.log +++ b/tests/baselines/reference/user/npmlog.log @@ -8,9 +8,9 @@ node_modules/npmlog/log.js(194,37): error TS2345: Argument of type 'any[]' is no Property '0' is missing in type 'any[]' but required in type '[any, ...any[]]'. node_modules/npmlog/log.js(218,12): error TS2551: Property '_paused' does not exist on type 'typeof EventEmitter'. Did you mean 'pause'? node_modules/npmlog/log.js(271,16): error TS2769: No overload matches this call. - Overload 1 of 2, '(buffer: string | Uint8Array | Buffer, cb?: ((err?: Error | null | undefined) => void) | undefined): boolean', gave the following error. - Argument of type 'string | undefined' is not assignable to parameter of type 'string | Uint8Array | Buffer'. - Type 'undefined' is not assignable to type 'string | Uint8Array | Buffer'. + Overload 1 of 2, '(buffer: string | Uint8Array, cb?: ((err?: Error | null | undefined) => void) | undefined): boolean', gave the following error. + Argument of type 'string | undefined' is not assignable to parameter of type 'string | Uint8Array'. + Type 'undefined' is not assignable to type 'string | Uint8Array'. Overload 2 of 2, '(str: string, encoding?: string | undefined, cb?: ((err?: Error | null | undefined) => void) | undefined): boolean', gave the following error. Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. From e543d8bc5a17bdee931ac1a0d2b9ddd32a7164a9 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 19 Jul 2019 15:22:04 -0700 Subject: [PATCH 033/151] Fix type keyword completions (#32474) * Fix type keyword completions 1. In functions, type keywords were omitted. 2. In All context, no keywords were omitted. (1) fixes #28737 (2) removes 17 keywords that should not be suggested, even at the toplevel of a typescript file: * private * protected * public * static * abstract * as * constructor * get * infer * is * namespace * require * set * type * from * global * of I don't know whether we have a bug tracking this or not. * Change keyword filter in filterGlobalCompletion Instead of changing FunctionLikeBodyKeywords * Add more tests cases * Make type-only completions after < more common Because isPossiblyTypeArgumentPosition doesn't give false positives now that it uses type information. --- src/harness/fourslash.ts | 43 +------------------ src/services/completions.ts | 38 +++++++++------- ...FunctionLikeBody_includesPrimitiveTypes.ts | 27 ++++++++++++ .../completionListInUnclosedTypeArguments.ts | 9 ++-- .../completionListIsGlobalCompletion.ts | 2 +- ...mpletionsIsPossiblyTypeArgumentPosition.ts | 17 +++----- tests/cases/fourslash/fourslash.ts | 1 - tests/cases/user/prettier/prettier | 2 +- 8 files changed, 64 insertions(+), 75 deletions(-) create mode 100644 tests/cases/fourslash/completionInFunctionLikeBody_includesPrimitiveTypes.ts diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index aa764e74cdc..f12506be2fb 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -797,7 +797,7 @@ namespace FourSlash { for (const include of toArray(options.includes)) { const name = typeof include === "string" ? include : include.name; const found = nameToEntries.get(name); - if (!found) throw this.raiseError(`No completion ${name} found`); + if (!found) throw this.raiseError(`Includes: completion '${name}' not found.`); assert(found.length === 1); // Must use 'exact' for multiple completions with same name this.verifyCompletionEntry(ts.first(found), include); } @@ -806,7 +806,7 @@ namespace FourSlash { for (const exclude of toArray(options.excludes)) { assert(typeof exclude === "string"); if (nameToEntries.has(exclude)) { - this.raiseError(`Did not expect to get a completion named ${exclude}`); + this.raiseError(`Excludes: unexpected completion '${exclude}' found.`); } } } @@ -4827,40 +4827,23 @@ namespace FourSlashInterface { "interface", "let", "package", - "private", - "protected", - "public", - "static", "yield", - "abstract", - "as", "any", "async", "await", "boolean", - "constructor", "declare", - "get", - "infer", - "is", "keyof", "module", - "namespace", "never", "readonly", - "require", "number", "object", - "set", "string", "symbol", - "type", "unique", "unknown", - "from", - "global", "bigint", - "of", ].map(keywordEntry); export const statementKeywords: ReadonlyArray = statementKeywordsWithTypes.filter(k => { @@ -5041,40 +5024,23 @@ namespace FourSlashInterface { "interface", "let", "package", - "private", - "protected", - "public", - "static", "yield", - "abstract", - "as", "any", "async", "await", "boolean", - "constructor", "declare", - "get", - "infer", - "is", "keyof", "module", - "namespace", "never", "readonly", - "require", "number", "object", - "set", "string", "symbol", - "type", "unique", "unknown", - "from", - "global", "bigint", - "of", ].map(keywordEntry); export const globalInJsKeywords = getInJsKeywords(globalKeywords); @@ -5127,11 +5093,6 @@ namespace FourSlashInterface { export const insideMethodInJsKeywords = getInJsKeywords(insideMethodKeywords); - export const globalKeywordsPlusUndefined: ReadonlyArray = (() => { - const i = ts.findIndex(globalKeywords, x => x.name === "unique"); - return [...globalKeywords.slice(0, i), keywordEntry("undefined"), ...globalKeywords.slice(i)]; - })(); - export const globals: ReadonlyArray = [ globalThisEntry, ...globalsVars, diff --git a/src/services/completions.ts b/src/services/completions.ts index b5c412a788a..e9a38fb1516 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -947,11 +947,13 @@ namespace ts.Completions { // Right of dot member completion list completionKind = CompletionKind.PropertyAccess; - // Since this is qualified name check its a type node location + // Since this is qualified name check it's a type node location const isImportType = isLiteralImportTypeNode(node); - const isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !(node as ImportTypeNode).isTypeOf) || isPartOfTypeNode(node.parent); + const isTypeLocation = insideJsDocTagTypeExpression + || (isImportType && !(node as ImportTypeNode).isTypeOf) + || isPartOfTypeNode(node.parent) + || isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node); - const allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); if (isEntityName(node) || isImportType) { const isNamespaceName = isModuleDeclaration(node.parent); if (isNamespaceName) isNewIdentifierLocation = true; @@ -968,7 +970,7 @@ namespace ts.Completions { isNamespaceName // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. ? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations.every(d => d.parent === node.parent) - : allowTypeOrValue ? + : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration symbol => isValidTypeAccess(symbol) || isValidValueAccess(symbol) : isTypeLocation ? isValidTypeAccess : isValidValueAccess; @@ -1181,7 +1183,6 @@ namespace ts.Completions { function filterGlobalCompletion(symbols: Symbol[]): void { const isTypeOnly = isTypeOnlyCompletion(); - const allowTypes = isTypeOnly || !isContextTokenValueLocation(contextToken) && isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnly) { keywordFilters = isTypeAssertion() ? KeywordCompletionFilters.TypeAssertionKeywords @@ -1202,12 +1203,9 @@ namespace ts.Completions { return !!(symbol.flags & SymbolFlags.Namespace); } - if (allowTypes) { - // Its a type, but you can reach it by namespace.type as well - const symbolAllowedAsType = symbolCanBeReferencedAtTypeLocation(symbol); - if (symbolAllowedAsType || isTypeOnly) { - return symbolAllowedAsType; - } + if (isTypeOnly) { + // It's a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol); } } @@ -1221,7 +1219,11 @@ namespace ts.Completions { } function isTypeOnlyCompletion(): boolean { - return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + return insideJsDocTagTypeExpression + || !isContextTokenValueLocation(contextToken) && + (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) + || isPartOfTypeNode(location) + || isContextTokenTypeLocation(contextToken)); } function isContextTokenValueLocation(contextToken: Node) { @@ -2060,16 +2062,18 @@ namespace ts.Completions { case KeywordCompletionFilters.None: return false; case KeywordCompletionFilters.All: - return kind === SyntaxKind.AsyncKeyword || SyntaxKind.AwaitKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === SyntaxKind.DeclareKeyword || kind === SyntaxKind.ModuleKeyword + return isFunctionLikeBodyKeyword(kind) + || kind === SyntaxKind.DeclareKeyword + || kind === SyntaxKind.ModuleKeyword || isTypeKeyword(kind) && kind !== SyntaxKind.UndefinedKeyword; + case KeywordCompletionFilters.FunctionLikeBodyKeywords: + return isFunctionLikeBodyKeyword(kind); case KeywordCompletionFilters.ClassElementKeywords: return isClassMemberCompletionKeyword(kind); case KeywordCompletionFilters.InterfaceElementKeywords: return isInterfaceOrTypeLiteralCompletionKeyword(kind); case KeywordCompletionFilters.ConstructorParameterKeywords: return isParameterPropertyModifier(kind); - case KeywordCompletionFilters.FunctionLikeBodyKeywords: - return isFunctionLikeBodyKeyword(kind); case KeywordCompletionFilters.TypeAssertionKeywords: return isTypeKeyword(kind) || kind === SyntaxKind.ConstKeyword; case KeywordCompletionFilters.TypeKeywords: @@ -2132,7 +2136,9 @@ namespace ts.Completions { } function isFunctionLikeBodyKeyword(kind: SyntaxKind) { - return kind === SyntaxKind.AsyncKeyword || kind === SyntaxKind.AwaitKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + return kind === SyntaxKind.AsyncKeyword + || kind === SyntaxKind.AwaitKeyword + || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node: Node): SyntaxKind { diff --git a/tests/cases/fourslash/completionInFunctionLikeBody_includesPrimitiveTypes.ts b/tests/cases/fourslash/completionInFunctionLikeBody_includesPrimitiveTypes.ts new file mode 100644 index 00000000000..bc94936ab43 --- /dev/null +++ b/tests/cases/fourslash/completionInFunctionLikeBody_includesPrimitiveTypes.ts @@ -0,0 +1,27 @@ +/// + +//// class Foo { } +//// class Bar { } +//// function includesTypes() { +//// new Foo ////f -////f(); +////f(); //// ////f2 ////f2 -////f2(); +////f2(); //// ////f2 { const markerName = test.markerName(marker) || ""; - const typeOnly = markerName.endsWith("TypeOnly") || marker.data && marker.data.typeOnly; const valueOnly = markerName.endsWith("ValueOnly"); verify.completions({ marker, - includes: typeOnly ? "Type" : valueOnly ? "x" : ["Type", "x"], - excludes: typeOnly ? "x" : valueOnly ? "Type" : [], + includes: valueOnly ? "x" : "Type", + excludes: valueOnly ? "Type" : "x", isNewIdentifierLocation: marker.data && marker.data.newId || false, }); }); diff --git a/tests/cases/fourslash/completionListIsGlobalCompletion.ts b/tests/cases/fourslash/completionListIsGlobalCompletion.ts index ea89155a771..91cd1a0f9c7 100644 --- a/tests/cases/fourslash/completionListIsGlobalCompletion.ts +++ b/tests/cases/fourslash/completionListIsGlobalCompletion.ts @@ -48,5 +48,5 @@ verify.completions( { marker: "13", exact: globals, isGlobalCompletion: false }, { marker: "15", exact: globals, isGlobalCompletion: true, isNewIdentifierLocation: true }, { marker: "16", exact: [...x, completion.globalThisEntry, ...completion.globalsVars, completion.undefinedVarEntry], isGlobalCompletion: false }, - { marker: "17", exact: completion.globalKeywordsPlusUndefined, isGlobalCompletion: false }, + { marker: "17", exact: completion.globalKeywords, isGlobalCompletion: false }, ); diff --git a/tests/cases/fourslash/completionsIsPossiblyTypeArgumentPosition.ts b/tests/cases/fourslash/completionsIsPossiblyTypeArgumentPosition.ts index 1ea8416d70b..704fe0d8347 100644 --- a/tests/cases/fourslash/completionsIsPossiblyTypeArgumentPosition.ts +++ b/tests/cases/fourslash/completionsIsPossiblyTypeArgumentPosition.ts @@ -9,25 +9,22 @@ ////x + {| "valueOnly": true |} ////x < {| "valueOnly": true |} ////f < {| "valueOnly": true |} -////g < {| "valueOnly": false |} -////const something: C<{| "typeOnly": true |}; -////const something2: C(): callAndConstruct; (): string; }; ////interface callAndConstruct {} ////new callAndConstruct; export const insideMethodKeywords: ReadonlyArray; export const insideMethodInJsKeywords: ReadonlyArray; - export const globalKeywordsPlusUndefined: ReadonlyArray; export const globalsVars: ReadonlyArray; export function globalsInsideFunction(plus: ReadonlyArray): ReadonlyArray; export function globalsInJsInsideFunction(plus: ReadonlyArray): ReadonlyArray; diff --git a/tests/cases/user/prettier/prettier b/tests/cases/user/prettier/prettier index 1e471a00796..7f938c71ffd 160000 --- a/tests/cases/user/prettier/prettier +++ b/tests/cases/user/prettier/prettier @@ -1 +1 @@ -Subproject commit 1e471a007968b7490563b91ed6909ae6046f3fe8 +Subproject commit 7f938c71ffda293eb1b69adf8bd12b7c11f9113b From aab3069e643952f5ddfe750fe3e5f196c16c3915 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 19 Jul 2019 15:55:22 -0700 Subject: [PATCH 034/151] Fix the assert of reporting file infos still attached to the project for circular json reference --- src/server/editorServices.ts | 19 ++++++++++++++++++- src/testRunner/unittests/tsserver/projects.ts | 17 +++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 81c56bb179b..df9f0e3ee01 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1087,7 +1087,24 @@ namespace ts.server { project.close(); if (Debug.shouldAssert(AssertionLevel.Normal)) { - this.filenameToScriptInfo.forEach(info => Debug.assert(!info.isAttached(project), "Found script Info still attached to project", () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify(mapDefined(arrayFrom(this.filenameToScriptInfo.values()), info => info.isAttached(project) ? info : undefined))}`)); + this.filenameToScriptInfo.forEach(info => Debug.assert( + !info.isAttached(project), + "Found script Info still attached to project", + () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify( + arrayFrom( + mapDefinedIterator( + this.filenameToScriptInfo.values(), + info => info.isAttached(project) ? + { + fileName: info.fileName, + projects: info.containingProjects.map(p => p.projectName), + hasMixedContent: info.hasMixedContent + } : undefined + ) + ), + /*replacer*/ undefined, + " " + )}`)); } // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 409ce5c525f..abb21669f8a 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -1467,5 +1467,22 @@ var x = 10;` openFilesForSession([{ file, projectRootPath }], session); } }); + + it("assert when removing project", () => { + const host = createServerHost([commonFile1, commonFile2, libFile]); + const service = createProjectService(host); + service.openClientFile(commonFile1.path); + const project = service.inferredProjects[0]; + checkProjectActualFiles(project, [commonFile1.path, libFile.path]); + // Intentionally create scriptinfo and attach it to project + const info = service.getOrCreateScriptInfoForNormalizedPath(commonFile2.path as server.NormalizedPath, /*openedByClient*/ false)!; + info.attachToProject(project); + try { + service.applyChangesInOpenFiles(/*openFiles*/ undefined, /*changedFiles*/ undefined, [commonFile1.path]); + } + catch (e) { + assert.isTrue(e.message.indexOf("Debug Failure. False expression: Found script Info still attached to project") === 0); + } + }); }); } From 2450c1947facf8101cb6cba2e030877ec28a0a88 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 20 Jul 2019 09:57:10 -0700 Subject: [PATCH 035/151] Make lower priority inferences when inference process is blocked --- src/compiler/checker.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f044ee8e375..c2510f84a19 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15459,6 +15459,7 @@ namespace ts { let bivariant = false; let propagationType: Type; let inferenceCount = 0; + let inferenceBlocked = false; let allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); @@ -15655,6 +15656,7 @@ namespace ts { if (source.flags & (TypeFlags.Object | TypeFlags.Intersection)) { const key = source.id + "," + target.id; if (visited && visited.get(key)) { + inferenceBlocked = true; return; } (visited || (visited = createMap())).set(key, true); @@ -15667,6 +15669,7 @@ namespace ts { const symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (contains(symbolStack, symbol)) { + inferenceBlocked = true; return; } (symbolStack || (symbolStack = [])).push(symbol); @@ -15755,6 +15758,8 @@ namespace ts { const sources = source.flags & TypeFlags.Union ? (source).types : [source]; const matched = new Array(sources.length); let typeVariableCount = 0; + const saveInferenceBlocked = inferenceBlocked; + inferenceBlocked = false; // First infer to types that are not naked type variables. For each source type we // track whether inferences were made from that particular type to some target. for (const t of target.types) { @@ -15771,14 +15776,15 @@ namespace ts { } // If there are naked type variables in the target, create a union of the source types // from which no inferences have been made so far and infer from that union to each naked - // type variable. If there is more than one naked type variable, give lower priority to - // the inferences as they are less specific. + // type variable. If there is more than one naked type variable, or if inference was blocked + // (meaning we didn't explore the types fully), give lower priority to the inferences as + // they are less specific. if (typeVariableCount > 0) { const unmatched = flatMap(sources, (s, i) => matched[i] ? undefined : s); if (unmatched.length) { const s = getUnionType(unmatched); const savePriority = priority; - if (typeVariableCount > 1) { + if (typeVariableCount > 1 || inferenceBlocked) { priority |= InferencePriority.NakedTypeVariable; } for (const t of target.types) { @@ -15789,6 +15795,7 @@ namespace ts { priority = savePriority; } } + inferenceBlocked = saveInferenceBlocked; } function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { From d96d16e10b1c307719314886a2a740735593a2e8 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 20 Jul 2019 10:01:59 -0700 Subject: [PATCH 036/151] Add additional test --- .../typeInference/unionTypeInference.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts index ccedb753354..4d9a3eae21e 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference.ts @@ -32,6 +32,17 @@ const d1 = f4("abc"); const d2 = f4(s); const d3 = f4(42); // Error +export interface Foo { + then(f: (x: T) => U | Foo, g: U): Foo; +} +export interface Bar { + then(f: (x: T) => S | Bar, g: S): Bar; +} + +function qux(p1: Foo, p2: Bar) { + p1 = p2; +} + // Repros from #32434 declare function foo(x: T | Promise): void; From 623a1725c8f7ae779eb754a0d5d9f29a7e633688 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 20 Jul 2019 10:02:46 -0700 Subject: [PATCH 037/151] Accept new baselines --- .../reference/unionTypeInference.errors.txt | 11 +++ .../baselines/reference/unionTypeInference.js | 15 ++++ .../reference/unionTypeInference.symbols | 83 +++++++++++++++---- .../reference/unionTypeInference.types | 26 ++++++ 4 files changed, 118 insertions(+), 17 deletions(-) diff --git a/tests/baselines/reference/unionTypeInference.errors.txt b/tests/baselines/reference/unionTypeInference.errors.txt index 2fe480d0a07..f28f32f3373 100644 --- a/tests/baselines/reference/unionTypeInference.errors.txt +++ b/tests/baselines/reference/unionTypeInference.errors.txt @@ -39,6 +39,17 @@ tests/cases/conformance/types/typeRelationships/typeInference/unionTypeInference ~~ !!! error TS2345: Argument of type '42' is not assignable to parameter of type 'never'. + export interface Foo { + then(f: (x: T) => U | Foo, g: U): Foo; + } + export interface Bar { + then(f: (x: T) => S | Bar, g: S): Bar; + } + + function qux(p1: Foo, p2: Bar) { + p1 = p2; + } + // Repros from #32434 declare function foo(x: T | Promise): void; diff --git a/tests/baselines/reference/unionTypeInference.js b/tests/baselines/reference/unionTypeInference.js index 868140e83a0..e41872eb4d4 100644 --- a/tests/baselines/reference/unionTypeInference.js +++ b/tests/baselines/reference/unionTypeInference.js @@ -31,6 +31,17 @@ const d1 = f4("abc"); const d2 = f4(s); const d3 = f4(42); // Error +export interface Foo { + then(f: (x: T) => U | Foo, g: U): Foo; +} +export interface Bar { + then(f: (x: T) => S | Bar, g: S): Bar; +} + +function qux(p1: Foo, p2: Bar) { + p1 = p2; +} + // Repros from #32434 declare function foo(x: T | Promise): void; @@ -43,6 +54,7 @@ const y = bar(1, 2); //// [unionTypeInference.js] "use strict"; +exports.__esModule = true; var a1 = f1(1, 2); // 1 | 2 var a2 = f1(1, "hello"); // 1 var a3 = f1(1, sn); // number @@ -59,5 +71,8 @@ var c5 = f3("abc"); // never var d1 = f4("abc"); var d2 = f4(s); var d3 = f4(42); // Error +function qux(p1, p2) { + p1 = p2; +} foo(x); var y = bar(1, 2); diff --git a/tests/baselines/reference/unionTypeInference.symbols b/tests/baselines/reference/unionTypeInference.symbols index 52b8809dee6..0d0bf6ae9be 100644 --- a/tests/baselines/reference/unionTypeInference.symbols +++ b/tests/baselines/reference/unionTypeInference.symbols @@ -107,34 +107,83 @@ const d3 = f4(42); // Error >d3 : Symbol(d3, Decl(unionTypeInference.ts, 30, 5)) >f4 : Symbol(f4, Decl(unionTypeInference.ts, 24, 21)) +export interface Foo { +>Foo : Symbol(Foo, Decl(unionTypeInference.ts, 30, 18)) +>T : Symbol(T, Decl(unionTypeInference.ts, 32, 21)) + + then(f: (x: T) => U | Foo, g: U): Foo; +>then : Symbol(Foo.then, Decl(unionTypeInference.ts, 32, 25)) +>U : Symbol(U, Decl(unionTypeInference.ts, 33, 9)) +>f : Symbol(f, Decl(unionTypeInference.ts, 33, 12)) +>x : Symbol(x, Decl(unionTypeInference.ts, 33, 16)) +>T : Symbol(T, Decl(unionTypeInference.ts, 32, 21)) +>U : Symbol(U, Decl(unionTypeInference.ts, 33, 9)) +>Foo : Symbol(Foo, Decl(unionTypeInference.ts, 30, 18)) +>U : Symbol(U, Decl(unionTypeInference.ts, 33, 9)) +>g : Symbol(g, Decl(unionTypeInference.ts, 33, 36)) +>U : Symbol(U, Decl(unionTypeInference.ts, 33, 9)) +>Foo : Symbol(Foo, Decl(unionTypeInference.ts, 30, 18)) +>U : Symbol(U, Decl(unionTypeInference.ts, 33, 9)) +} +export interface Bar { +>Bar : Symbol(Bar, Decl(unionTypeInference.ts, 34, 1)) +>T : Symbol(T, Decl(unionTypeInference.ts, 35, 21)) + + then(f: (x: T) => S | Bar, g: S): Bar; +>then : Symbol(Bar.then, Decl(unionTypeInference.ts, 35, 25)) +>S : Symbol(S, Decl(unionTypeInference.ts, 36, 9)) +>f : Symbol(f, Decl(unionTypeInference.ts, 36, 12)) +>x : Symbol(x, Decl(unionTypeInference.ts, 36, 16)) +>T : Symbol(T, Decl(unionTypeInference.ts, 35, 21)) +>S : Symbol(S, Decl(unionTypeInference.ts, 36, 9)) +>Bar : Symbol(Bar, Decl(unionTypeInference.ts, 34, 1)) +>S : Symbol(S, Decl(unionTypeInference.ts, 36, 9)) +>g : Symbol(g, Decl(unionTypeInference.ts, 36, 36)) +>S : Symbol(S, Decl(unionTypeInference.ts, 36, 9)) +>Bar : Symbol(Bar, Decl(unionTypeInference.ts, 34, 1)) +>S : Symbol(S, Decl(unionTypeInference.ts, 36, 9)) +} + +function qux(p1: Foo, p2: Bar) { +>qux : Symbol(qux, Decl(unionTypeInference.ts, 37, 1)) +>p1 : Symbol(p1, Decl(unionTypeInference.ts, 39, 13)) +>Foo : Symbol(Foo, Decl(unionTypeInference.ts, 30, 18)) +>p2 : Symbol(p2, Decl(unionTypeInference.ts, 39, 27)) +>Bar : Symbol(Bar, Decl(unionTypeInference.ts, 34, 1)) + + p1 = p2; +>p1 : Symbol(p1, Decl(unionTypeInference.ts, 39, 13)) +>p2 : Symbol(p2, Decl(unionTypeInference.ts, 39, 27)) +} + // Repros from #32434 declare function foo(x: T | Promise): void; ->foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 18)) ->T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) ->x : Symbol(x, Decl(unionTypeInference.ts, 34, 24)) ->T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) +>foo : Symbol(foo, Decl(unionTypeInference.ts, 41, 1)) +>T : Symbol(T, Decl(unionTypeInference.ts, 45, 21)) +>x : Symbol(x, Decl(unionTypeInference.ts, 45, 24)) +>T : Symbol(T, Decl(unionTypeInference.ts, 45, 21)) >Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(unionTypeInference.ts, 34, 21)) +>T : Symbol(T, Decl(unionTypeInference.ts, 45, 21)) declare let x: false | Promise; ->x : Symbol(x, Decl(unionTypeInference.ts, 35, 11)) +>x : Symbol(x, Decl(unionTypeInference.ts, 46, 11)) >Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) foo(x); ->foo : Symbol(foo, Decl(unionTypeInference.ts, 30, 18)) ->x : Symbol(x, Decl(unionTypeInference.ts, 35, 11)) +>foo : Symbol(foo, Decl(unionTypeInference.ts, 41, 1)) +>x : Symbol(x, Decl(unionTypeInference.ts, 46, 11)) declare function bar(x: T, y: string | T): T; ->bar : Symbol(bar, Decl(unionTypeInference.ts, 36, 7)) ->T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) ->x : Symbol(x, Decl(unionTypeInference.ts, 38, 24)) ->T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) ->y : Symbol(y, Decl(unionTypeInference.ts, 38, 29)) ->T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) ->T : Symbol(T, Decl(unionTypeInference.ts, 38, 21)) +>bar : Symbol(bar, Decl(unionTypeInference.ts, 47, 7)) +>T : Symbol(T, Decl(unionTypeInference.ts, 49, 21)) +>x : Symbol(x, Decl(unionTypeInference.ts, 49, 24)) +>T : Symbol(T, Decl(unionTypeInference.ts, 49, 21)) +>y : Symbol(y, Decl(unionTypeInference.ts, 49, 29)) +>T : Symbol(T, Decl(unionTypeInference.ts, 49, 21)) +>T : Symbol(T, Decl(unionTypeInference.ts, 49, 21)) const y = bar(1, 2); ->y : Symbol(y, Decl(unionTypeInference.ts, 39, 5)) ->bar : Symbol(bar, Decl(unionTypeInference.ts, 36, 7)) +>y : Symbol(y, Decl(unionTypeInference.ts, 50, 5)) +>bar : Symbol(bar, Decl(unionTypeInference.ts, 47, 7)) diff --git a/tests/baselines/reference/unionTypeInference.types b/tests/baselines/reference/unionTypeInference.types index e6d47fa4bda..6675e63f8c4 100644 --- a/tests/baselines/reference/unionTypeInference.types +++ b/tests/baselines/reference/unionTypeInference.types @@ -131,6 +131,32 @@ const d3 = f4(42); // Error >f4 : (x: string & T) => T >42 : 42 +export interface Foo { + then(f: (x: T) => U | Foo, g: U): Foo; +>then : (f: (x: T) => U | Foo, g: U) => Foo +>f : (x: T) => U | Foo +>x : T +>g : U +} +export interface Bar { + then(f: (x: T) => S | Bar, g: S): Bar; +>then : (f: (x: T) => S | Bar, g: S) => Bar +>f : (x: T) => S | Bar +>x : T +>g : S +} + +function qux(p1: Foo, p2: Bar) { +>qux : (p1: Foo, p2: Bar) => void +>p1 : Foo +>p2 : Bar + + p1 = p2; +>p1 = p2 : Bar +>p1 : Foo +>p2 : Bar +} + // Repros from #32434 declare function foo(x: T | Promise): void; From 2541a5d0fff2037854732253dfc74a096d4c1c04 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 20 Jul 2019 14:33:35 -0700 Subject: [PATCH 038/151] Always infer between distinct type references to same target --- src/compiler/checker.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0b4ae0d9d33..7b39ce98b93 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15958,9 +15958,14 @@ namespace ts { } } + function isTypeReferenceToSameTarget(source: Type, target: Type) { + return !!(getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && + (source).target === (target).target); + } + function typeIdenticalToSomeType(type: Type, types: Type[]): boolean { for (const t of types) { - if (isTypeIdenticalTo(t, type)) { + if (t === type || !isTypeReferenceToSameTarget(t, type) && isTypeIdenticalTo(t, type)) { return true; } } From 9b2d9cdffcc540d875b0cab533b9915337fa2097 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 21 Jul 2019 14:07:45 -0700 Subject: [PATCH 039/151] Fix issues uncovered by DT tests --- src/compiler/checker.ts | 50 +++++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7b39ce98b93..19517b6715c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13540,6 +13540,9 @@ namespace ts { if (relation !== identityRelation) { source = getApparentType(source); } + else if (isGenericMappedType(source)) { + return Ternary.False; + } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target && !(getObjectFlags(source) & ObjectFlags.MarkerType || getObjectFlags(target) & ObjectFlags.MarkerType)) { // We have type references to the same generic type, and the type references are not marker @@ -15456,7 +15459,7 @@ namespace ts { function inferTypes(inferences: InferenceInfo[], originalSource: Type, originalTarget: Type, priority: InferencePriority = 0, contravariant = false) { let symbolStack: Symbol[]; - let visited: Map; + let visited: Map; let bivariant = false; let propagationType: Type; let inferenceCount = 0; @@ -15656,15 +15659,17 @@ namespace ts { } if (source.flags & (TypeFlags.Object | TypeFlags.Intersection)) { const key = source.id + "," + target.id; - if (visited && visited.get(key)) { - inferenceBlocked = true; + const visitCount = visited && visited.get(key); + if (visitCount !== undefined) { + inferenceCount += visitCount; return; } - (visited || (visited = createMap())).set(key, true); + (visited || (visited = createMap())).set(key, 0); // If we are already processing another target type with the same associated symbol (such as // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. + const startCount = inferenceCount; const isNonConstructorObject = target.flags & TypeFlags.Object && !(getObjectFlags(target) & ObjectFlags.Anonymous && target.symbol && target.symbol.flags & SymbolFlags.Class); const symbol = isNonConstructorObject ? target.symbol : undefined; @@ -15680,14 +15685,21 @@ namespace ts { else { inferFromObjectTypes(source, target); } + visited.set(key, inferenceCount - startCount); } } function inferFromTypesOnce(source: Type, target: Type) { const key = source.id + "," + target.id; - if (!visited || !visited.get(key)) { - (visited || (visited = createMap())).set(key, true); + const count = visited && visited.get(key); + if (count !== undefined) { + inferenceCount += count; + } + else { + (visited || (visited = createMap())).set(key, 0); + const startCount = inferenceCount; inferFromTypes(source, target); + visited.set(key, inferenceCount - startCount); } } } @@ -15780,23 +15792,28 @@ namespace ts { // type variable. If there is more than one naked type variable, or if inference was blocked // (meaning we didn't explore the types fully), give lower priority to the inferences as // they are less specific. - if (typeVariableCount > 0) { + if (typeVariableCount === 1 && !inferenceBlocked) { const unmatched = flatMap(sources, (s, i) => matched[i] ? undefined : s); if (unmatched.length) { const s = getUnionType(unmatched); - const savePriority = priority; - if (typeVariableCount > 1 || inferenceBlocked) { - priority |= InferencePriority.NakedTypeVariable; - } for (const t of target.types) { if (getInferenceInfoForType(t)) { inferFromTypes(s, t); } } - priority = savePriority; } } - inferenceBlocked = saveInferenceBlocked; + inferenceBlocked = inferenceBlocked || saveInferenceBlocked; + if (typeVariableCount > 0) { + const savePriority = priority; + priority |= InferencePriority.NakedTypeVariable; + for (const t of target.types) { + if (getInferenceInfoForType(t)) { + inferFromTypes(source, t); + } + } + priority = savePriority; + } } function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { @@ -15958,14 +15975,13 @@ namespace ts { } } - function isTypeReferenceToSameTarget(source: Type, target: Type) { - return !!(getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && - (source).target === (target).target); + function isMatchableType(type: Type) { + return !(type.flags & TypeFlags.Object) || !!(getObjectFlags(type) & ObjectFlags.Anonymous); } function typeIdenticalToSomeType(type: Type, types: Type[]): boolean { for (const t of types) { - if (t === type || !isTypeReferenceToSameTarget(t, type) && isTypeIdenticalTo(t, type)) { + if (t === type || isMatchableType(t) && isMatchableType(type) && isTypeIdenticalTo(t, type)) { return true; } } From 203fd9ff9e1a9923a7dc663cc738c4072b6431ee Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 22 Jul 2019 08:01:22 -0700 Subject: [PATCH 040/151] Combine multiple separate code paths --- src/compiler/checker.ts | 195 ++++++++++++++++++---------------------- 1 file changed, 87 insertions(+), 108 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 19517b6715c..9f64e13911c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15577,7 +15577,7 @@ namespace ts { // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine const simplified = getSimplifiedType(target, /*writing*/ false); if (simplified !== target) { - inferFromTypesOnce(source, simplified); + invokeOnce(source, simplified, inferFromTypes); } else if (target.flags & TypeFlags.IndexedAccess) { const indexType = getSimplifiedType((target as IndexedAccessType).indexType, /*writing*/ false); @@ -15586,7 +15586,7 @@ namespace ts { if (indexType.flags & TypeFlags.Instantiable) { const simplified = distributeIndexOverObjectType(getSimplifiedType((target as IndexedAccessType).objectType, /*writing*/ false), indexType, /*writing*/ false); if (simplified && simplified !== target) { - inferFromTypesOnce(source, simplified); + invokeOnce(source, simplified, inferFromTypes); } } } @@ -15621,15 +15621,12 @@ namespace ts { inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & TypeFlags.Union) { - inferToUnionType(source, target); - } - else if (target.flags & TypeFlags.Intersection) { - inferToMultipleTypes(source, (target).types, /*isIntersection*/ true); - } else if (target.flags & TypeFlags.Conditional && !contravariant) { const targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; - inferToMultipleTypes(source, targetTypes, /*isIntersection*/ false); + inferToMultipleTypes(source, targetTypes, target.flags); + } + else if (target.flags & TypeFlags.UnionOrIntersection) { + inferToMultipleTypes(source, (target).types, target.flags); } else if (source.flags & TypeFlags.Union) { // Source is a union or intersection type, infer from each constituent type @@ -15658,50 +15655,22 @@ namespace ts { source = apparentSource; } if (source.flags & (TypeFlags.Object | TypeFlags.Intersection)) { - const key = source.id + "," + target.id; - const visitCount = visited && visited.get(key); - if (visitCount !== undefined) { - inferenceCount += visitCount; - return; - } - (visited || (visited = createMap())).set(key, 0); - // If we are already processing another target type with the same associated symbol (such as - // an instantiation of the same generic type), we do not explore this target as it would yield - // no further inferences. We exclude the static side of classes from this check since it shares - // its symbol with the instance side which would lead to false positives. - const startCount = inferenceCount; - const isNonConstructorObject = target.flags & TypeFlags.Object && - !(getObjectFlags(target) & ObjectFlags.Anonymous && target.symbol && target.symbol.flags & SymbolFlags.Class); - const symbol = isNonConstructorObject ? target.symbol : undefined; - if (symbol) { - if (contains(symbolStack, symbol)) { - inferenceBlocked = true; - return; - } - (symbolStack || (symbolStack = [])).push(symbol); - inferFromObjectTypes(source, target); - symbolStack.pop(); - } - else { - inferFromObjectTypes(source, target); - } - visited.set(key, inferenceCount - startCount); + invokeOnce(source, target, inferFromObjectTypes); } } + } - function inferFromTypesOnce(source: Type, target: Type) { - const key = source.id + "," + target.id; - const count = visited && visited.get(key); - if (count !== undefined) { - inferenceCount += count; - } - else { - (visited || (visited = createMap())).set(key, 0); - const startCount = inferenceCount; - inferFromTypes(source, target); - visited.set(key, inferenceCount - startCount); - } + function invokeOnce(source: Type, target: Type, action: (source: Type, target: Type) => void) { + const key = source.id + "," + target.id; + const count = visited && visited.get(key); + if (count !== undefined) { + inferenceCount += count; + return; } + (visited || (visited = createMap())).set(key, 0); + const startCount = inferenceCount; + action(source, target); + visited.set(key, inferenceCount - startCount); } function inferFromTypeArguments(sourceTypes: readonly Type[], targetTypes: readonly Type[], variances: readonly VarianceFlags[]) { @@ -15738,24 +15707,61 @@ namespace ts { return undefined; } - function inferToMultipleTypes(source: Type, targets: Type[], isIntersection: boolean) { - // We infer from types that are not naked type variables first so that inferences we - // make from nested naked type variables and given slightly higher priority by virtue - // of being first in the candidates array. + function inferToMultipleTypes(source: Type, targets: Type[], targetFlags: TypeFlags) { let typeVariableCount = 0; - for (const t of targets) { - if (getInferenceInfoForType(t)) { - typeVariableCount++; + if (targetFlags & TypeFlags.Union) { + const sources = source.flags & TypeFlags.Union ? (source).types : [source]; + const matched = new Array(sources.length); + const saveInferenceBlocked = inferenceBlocked; + inferenceBlocked = false; + // First infer to types that are not naked type variables. For each source type we + // track whether inferences were made from that particular type to some target. + for (const t of targets) { + if (getInferenceInfoForType(t)) { + typeVariableCount++; + } + else { + for (let i = 0; i < sources.length; i++) { + const count = inferenceCount; + inferFromTypes(sources[i], t); + if (count !== inferenceCount) matched[i] = true; + } + } } - else { - inferFromTypes(source, t); + // If the target has a single naked type variable and inference wasn't blocked (meaning + // we explored the types fully), create a union of the source types from which no inferences + // have been made so far and infer from that union to the naked type variable. + if (typeVariableCount === 1 && !inferenceBlocked) { + const unmatched = flatMap(sources, (s, i) => matched[i] ? undefined : s); + if (unmatched.length) { + const s = getUnionType(unmatched); + for (const t of targets) { + if (getInferenceInfoForType(t)) { + inferFromTypes(s, t); + } + } + } + } + inferenceBlocked = inferenceBlocked || saveInferenceBlocked; + } + else { + // We infer from types that are not naked type variables first so that inferences we + // make from nested naked type variables and given slightly higher priority by virtue + // of being first in the candidates array. + for (const t of targets) { + if (getInferenceInfoForType(t)) { + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } } } // Inferences directly to naked type variables are given lower priority as they are // less specific. For example, when inferring from Promise to T | Promise, // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. - if (isIntersection ? typeVariableCount === 1 : typeVariableCount !== 0) { + if (targetFlags & TypeFlags.Intersection ? typeVariableCount === 1 : typeVariableCount > 0) { const savePriority = priority; priority |= InferencePriority.NakedTypeVariable; for (const t of targets) { @@ -15767,55 +15773,6 @@ namespace ts { } } - function inferToUnionType(source: Type, target: UnionType) { - const sources = source.flags & TypeFlags.Union ? (source).types : [source]; - const matched = new Array(sources.length); - let typeVariableCount = 0; - const saveInferenceBlocked = inferenceBlocked; - inferenceBlocked = false; - // First infer to types that are not naked type variables. For each source type we - // track whether inferences were made from that particular type to some target. - for (const t of target.types) { - if (getInferenceInfoForType(t)) { - typeVariableCount++; - } - else { - for (let i = 0; i < sources.length; i++) { - const count = inferenceCount; - inferFromTypes(sources[i], t); - if (count !== inferenceCount) matched[i] = true; - } - } - } - // If there are naked type variables in the target, create a union of the source types - // from which no inferences have been made so far and infer from that union to each naked - // type variable. If there is more than one naked type variable, or if inference was blocked - // (meaning we didn't explore the types fully), give lower priority to the inferences as - // they are less specific. - if (typeVariableCount === 1 && !inferenceBlocked) { - const unmatched = flatMap(sources, (s, i) => matched[i] ? undefined : s); - if (unmatched.length) { - const s = getUnionType(unmatched); - for (const t of target.types) { - if (getInferenceInfoForType(t)) { - inferFromTypes(s, t); - } - } - } - } - inferenceBlocked = inferenceBlocked || saveInferenceBlocked; - if (typeVariableCount > 0) { - const savePriority = priority; - priority |= InferencePriority.NakedTypeVariable; - for (const t of target.types) { - if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); - } - } - priority = savePriority; - } - } - function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { if (constraintType.flags & TypeFlags.Union) { let result = false; @@ -15873,6 +15830,28 @@ namespace ts { } function inferFromObjectTypes(source: Type, target: Type) { + // If we are already processing another target type with the same associated symbol (such as + // an instantiation of the same generic type), we do not explore this target as it would yield + // no further inferences. We exclude the static side of classes from this check since it shares + // its symbol with the instance side which would lead to false positives. + const isNonConstructorObject = target.flags & TypeFlags.Object && + !(getObjectFlags(target) & ObjectFlags.Anonymous && target.symbol && target.symbol.flags & SymbolFlags.Class); + const symbol = isNonConstructorObject ? target.symbol : undefined; + if (symbol) { + if (contains(symbolStack, symbol)) { + inferenceBlocked = true; + return; + } + (symbolStack || (symbolStack = [])).push(symbol); + inferFromObjectTypesWorker(source, target); + symbolStack.pop(); + } + else { + inferFromObjectTypesWorker(source, target); + } + } + + function inferFromObjectTypesWorker(source: Type, target: Type) { if (isGenericMappedType(source) && isGenericMappedType(target)) { // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer // from S to T and from X to Y. From b822def6effe8521d14b218bf3287d83c761de21 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 22 Jul 2019 11:07:33 -0700 Subject: [PATCH 041/151] Minor cleanup plus more comments --- src/compiler/checker.ts | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9f64e13911c..0a64e0552e2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15463,7 +15463,7 @@ namespace ts { let bivariant = false; let propagationType: Type; let inferenceCount = 0; - let inferenceBlocked = false; + let inferenceIncomplete = false; let allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); @@ -15710,14 +15710,16 @@ namespace ts { function inferToMultipleTypes(source: Type, targets: Type[], targetFlags: TypeFlags) { let typeVariableCount = 0; if (targetFlags & TypeFlags.Union) { + let nakedTypeVariable: Type | undefined; const sources = source.flags & TypeFlags.Union ? (source).types : [source]; const matched = new Array(sources.length); - const saveInferenceBlocked = inferenceBlocked; - inferenceBlocked = false; + const saveInferenceIncomplete = inferenceIncomplete; + inferenceIncomplete = false; // First infer to types that are not naked type variables. For each source type we // track whether inferences were made from that particular type to some target. for (const t of targets) { if (getInferenceInfoForType(t)) { + nakedTypeVariable = t; typeVariableCount++; } else { @@ -15728,21 +15730,18 @@ namespace ts { } } } - // If the target has a single naked type variable and inference wasn't blocked (meaning - // we explored the types fully), create a union of the source types from which no inferences + const inferenceComplete = !inferenceIncomplete; + inferenceIncomplete = inferenceIncomplete || saveInferenceIncomplete; + // If the target has a single naked type variable and inference completed (meaning we + // explored the types fully), create a union of the source types from which no inferences // have been made so far and infer from that union to the naked type variable. - if (typeVariableCount === 1 && !inferenceBlocked) { + if (typeVariableCount === 1 && inferenceComplete) { const unmatched = flatMap(sources, (s, i) => matched[i] ? undefined : s); if (unmatched.length) { - const s = getUnionType(unmatched); - for (const t of targets) { - if (getInferenceInfoForType(t)) { - inferFromTypes(s, t); - } - } + inferFromTypes(getUnionType(unmatched), nakedTypeVariable!); + return; } } - inferenceBlocked = inferenceBlocked || saveInferenceBlocked; } else { // We infer from types that are not naked type variables first so that inferences we @@ -15839,7 +15838,7 @@ namespace ts { const symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { if (contains(symbolStack, symbol)) { - inferenceBlocked = true; + inferenceIncomplete = true; return; } (symbolStack || (symbolStack = [])).push(symbol); @@ -15955,10 +15954,13 @@ namespace ts { } function isMatchableType(type: Type) { + // We exclude non-anonymous object types because some frameworks (e.g. Ember) rely on the ability to + // infer between types that don't witness their type variables. Such types would otherwise be eliminated + // because they appear identical. return !(type.flags & TypeFlags.Object) || !!(getObjectFlags(type) & ObjectFlags.Anonymous); } - function typeIdenticalToSomeType(type: Type, types: Type[]): boolean { + function typeMatchedBySomeType(type: Type, types: Type[]): boolean { for (const t of types) { if (t === type || isMatchableType(t) && isMatchableType(type) && isTypeIdenticalTo(t, type)) { return true; @@ -15968,12 +15970,12 @@ namespace ts { } function findMatchedType(type: Type, target: UnionOrIntersectionType) { - if (typeIdenticalToSomeType(type, target.types)) { + if (typeMatchedBySomeType(type, target.types)) { return type; } if (type.flags & (TypeFlags.NumberLiteral | TypeFlags.StringLiteral) && target.flags & TypeFlags.Union) { const base = getBaseTypeOfLiteralType(type); - if (typeIdenticalToSomeType(base, target.types)) { + if (typeMatchedBySomeType(base, target.types)) { return base; } } @@ -15987,7 +15989,7 @@ namespace ts { function removeTypesFromUnionOrIntersection(type: UnionOrIntersectionType, typesToRemove: Type[]) { const reducedTypes: Type[] = []; for (const t of type.types) { - if (!typeIdenticalToSomeType(t, typesToRemove)) { + if (!typeMatchedBySomeType(t, typesToRemove)) { reducedTypes.push(t); } } From 47e3fedb5dda79bcaa33b1e9d424a8591b7f4c40 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 22 Jul 2019 16:46:09 -0700 Subject: [PATCH 042/151] Fix object spread runtime semantics (#32514) --- src/compiler/transformers/es2018.ts | 31 +++++++- src/testRunner/tsconfig.json | 1 + .../unittests/evaluation/objectRest.ts | 28 +++++++ ...iveInternalTypesProduceUniqueTypeParams.js | 2 +- .../excessPropertyCheckWithSpread.js | 2 +- .../reference/genericIsNeverEmptyObject.js | 2 +- .../objectLiteralFreshnessWithSpread.js | 2 +- .../reference/objectLiteralNormalization.js | 2 +- tests/baselines/reference/objectRestForOf.js | 2 +- tests/baselines/reference/objectSpread.js | 76 +++++++++---------- .../reference/objectSpreadComputedProperty.js | 2 +- .../reference/objectSpreadIndexSignature.js | 4 +- .../reference/objectSpreadNegative.js | 8 +- .../reference/objectSpreadNegativeParse.js | 2 +- .../reference/objectSpreadStrictNull.js | 20 ++--- ...preadWithinMethodWithinObjectWithSpread.js | 4 +- .../spreadContextualTypedBindingPattern.js | 2 +- .../baselines/reference/spreadIntersection.js | 2 +- .../baselines/reference/spreadNonPrimitive.js | 2 +- tests/baselines/reference/spreadUnion.js | 4 +- tests/baselines/reference/spreadUnion2.js | 8 +- tests/baselines/reference/spreadUnion3.js | 2 +- .../unionExcessPropsWithPartialMember.js | 2 +- tests/baselines/reference/unknownType1.js | 4 +- ...useBeforeDeclaration_propertyAssignment.js | 2 +- 25 files changed, 135 insertions(+), 81 deletions(-) create mode 100644 src/testRunner/unittests/evaluation/objectRest.ts diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index 89c43dcf599..50fb9f04d1a 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -229,14 +229,39 @@ namespace ts { if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: - // { a, ...o, b } => __assign({a}, o, {b}); + // { a, ...o, b } => __assign(__assign({a}, o), {b}); // If the first element is a spread element, then the first argument to __assign is {}: - // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) + // { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2) + // + // We cannot call __assign with more than two elements, since any element could cause side effects. For + // example: + // var k = { a: 1, b: 2 }; + // var o = { a: 3, ...k, b: k.a++ }; + // // expected: { a: 1, b: 1 } + // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before + // `k` is spread and we end up with `{ a: 2, b: 1 }`. + // + // This also occurs for spread elements, not just property assignments: + // var k = { a: 1, get b() { l = { z: 9 }; return 2; } }; + // var l = { c: 3 }; + // var o = { ...k, ...l }; + // // expected: { a: 1, b: 2, z: 9 } + // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we + // end up with `{ a: 1, b: 2, c: 3 }` const objects = chunkObjectLiteralElements(node.properties); if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) { objects.unshift(createObjectLiteral()); } - return createAssignHelper(context, objects); + let expression: Expression = objects[0]; + if (objects.length > 1) { + for (let i = 1; i < objects.length; i++) { + expression = createAssignHelper(context, [expression, objects[i]]); + } + return expression; + } + else { + return createAssignHelper(context, objects); + } } return visitEachChild(node, visitor, context); } diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index b2e7e3e78b9..9ea6c4c85ce 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -74,6 +74,7 @@ "unittests/evaluation/asyncArrow.ts", "unittests/evaluation/asyncGenerator.ts", "unittests/evaluation/forAwaitOf.ts", + "unittests/evaluation/objectRest.ts", "unittests/services/cancellableLanguageServiceOperations.ts", "unittests/services/colorization.ts", "unittests/services/convertToAsyncFunction.ts", diff --git a/src/testRunner/unittests/evaluation/objectRest.ts b/src/testRunner/unittests/evaluation/objectRest.ts new file mode 100644 index 00000000000..272ba51ffbe --- /dev/null +++ b/src/testRunner/unittests/evaluation/objectRest.ts @@ -0,0 +1,28 @@ +describe("unittests:: evaluation:: objectRest", () => { + // https://github.com/microsoft/TypeScript/issues/31469 + it("side effects in property assignment", async () => { + const result = evaluator.evaluateTypeScript(` + const k = { a: 1, b: 2 }; + const o = { a: 3, ...k, b: k.a++ }; + export const output = o; + `); + assert.deepEqual(result.output, { a: 1, b: 1 }); + }); + it("side effects in during spread", async () => { + const result = evaluator.evaluateTypeScript(` + const k = { a: 1, get b() { l = { c: 9 }; return 2; } }; + let l = { c: 3 }; + const o = { ...k, ...l }; + export const output = o; + `); + assert.deepEqual(result.output, { a: 1, b: 2, c: 9 }); + }); + it("trailing literal-valued object-literal", async () => { + const result = evaluator.evaluateTypeScript(` + const k = { a: 1 } + const o = { ...k, ...{ b: 2 } }; + export const output = o; + `); + assert.deepEqual(result.output, { a: 1, b: 2 }); + }); +}); diff --git a/tests/baselines/reference/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.js b/tests/baselines/reference/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.js index 913e82292bf..b043fe275cc 100644 --- a/tests/baselines/reference/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.js +++ b/tests/baselines/reference/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.js @@ -73,7 +73,7 @@ exports.testRecFun = function (parent) { return { result: parent, deeper: function (child) { - return exports.testRecFun(__assign({}, parent, child)); + return exports.testRecFun(__assign(__assign({}, parent), child)); } }; }; diff --git a/tests/baselines/reference/excessPropertyCheckWithSpread.js b/tests/baselines/reference/excessPropertyCheckWithSpread.js index c08e4738965..1b105de7918 100644 --- a/tests/baselines/reference/excessPropertyCheckWithSpread.js +++ b/tests/baselines/reference/excessPropertyCheckWithSpread.js @@ -30,4 +30,4 @@ var __assign = (this && this.__assign) || function () { return __assign.apply(this, arguments); }; f(__assign({ a: 1 }, i)); -f(__assign({ a: 1 }, l, r)); +f(__assign(__assign({ a: 1 }, l), r)); diff --git a/tests/baselines/reference/genericIsNeverEmptyObject.js b/tests/baselines/reference/genericIsNeverEmptyObject.js index 692f34bfcc4..ec489da75a9 100644 --- a/tests/baselines/reference/genericIsNeverEmptyObject.js +++ b/tests/baselines/reference/genericIsNeverEmptyObject.js @@ -37,7 +37,7 @@ var __rest = (this && this.__rest) || function (s, e) { }; function test(obj) { var a = obj.a, rest = __rest(obj, ["a"]); - return __assign({}, rest, { b: a }); + return __assign(__assign({}, rest), { b: a }); } var o1 = { a: 'hello', x: 42 }; var o2 = test(o1); diff --git a/tests/baselines/reference/objectLiteralFreshnessWithSpread.js b/tests/baselines/reference/objectLiteralFreshnessWithSpread.js index 73962db32ab..ad87fd0557d 100644 --- a/tests/baselines/reference/objectLiteralFreshnessWithSpread.js +++ b/tests/baselines/reference/objectLiteralFreshnessWithSpread.js @@ -16,4 +16,4 @@ var __assign = (this && this.__assign) || function () { return __assign.apply(this, arguments); }; var x = { b: 1, extra: 2 }; -var xx = __assign({ a: 1 }, x, { z: 3 }); // error for 'z', no error for 'extra' +var xx = __assign(__assign({ a: 1 }, x), { z: 3 }); // error for 'z', no error for 'extra' diff --git a/tests/baselines/reference/objectLiteralNormalization.js b/tests/baselines/reference/objectLiteralNormalization.js index 1a8aa8d4b04..aa37bdc2c5e 100644 --- a/tests/baselines/reference/objectLiteralNormalization.js +++ b/tests/baselines/reference/objectLiteralNormalization.js @@ -80,7 +80,7 @@ a2 = { a: "def" }; a2 = {}; a2 = { a: "def", b: 20 }; // Error a2 = { a: 1 }; // Error -var b2 = __assign({}, b1, { z: 55 }); +var b2 = __assign(__assign({}, b1), { z: 55 }); var b3 = __assign({}, b2); var c1 = !true ? {} : opts; var c2 = !true ? opts : {}; diff --git a/tests/baselines/reference/objectRestForOf.js b/tests/baselines/reference/objectRestForOf.js index f946e42444c..49ebf7c4c17 100644 --- a/tests/baselines/reference/objectRestForOf.js +++ b/tests/baselines/reference/objectRestForOf.js @@ -37,7 +37,7 @@ for (let _b of array) { ({ x: xx } = _b, rrestOff = __rest(_b, ["x"])); [xx, rrestOff]; } -for (const norest of array.map(a => (Object.assign({}, a, { x: 'a string' })))) { +for (const norest of array.map(a => (Object.assign(Object.assign({}, a), { x: 'a string' })))) { [norest.x, norest.y]; // x is now a string. who knows why. } diff --git a/tests/baselines/reference/objectSpread.js b/tests/baselines/reference/objectSpread.js index b7d3e858c79..1265cc889ff 100644 --- a/tests/baselines/reference/objectSpread.js +++ b/tests/baselines/reference/objectSpread.js @@ -171,45 +171,45 @@ var __assign = (this && this.__assign) || function () { var o = { a: 1, b: 'no' }; var o2 = { b: 'yes', c: true }; var swap = { a: 'yes', b: -1 }; -var addAfter = __assign({}, o, { c: false }); +var addAfter = __assign(__assign({}, o), { c: false }); var addBefore = __assign({ c: false }, o); // Note: ignore still changes the order that properties are printed var ignore = __assign({ b: 'ignored' }, o); -var override = __assign({}, o, { b: 'override' }); -var nested = __assign({}, __assign({ a: 3 }, { b: false, c: 'overriden' }), { c: 'whatever' }); -var combined = __assign({}, o, o2); -var combinedBefore = __assign({ b: 'ok' }, o, o2); -var combinedMid = __assign({}, o, { b: 'ok' }, o2); -var combinedAfter = __assign({}, o, o2, { b: 'ok' }); -var combinedNested = __assign({}, __assign({ a: 4 }, { b: false, c: 'overriden' }), { d: 'actually new' }, { a: 5, d: 'maybe new' }); -var combinedNestedChangeType = __assign({}, __assign({ a: 1 }, { b: false, c: 'overriden' }), { c: -1 }); +var override = __assign(__assign({}, o), { b: 'override' }); +var nested = __assign(__assign({}, __assign({ a: 3 }, { b: false, c: 'overriden' })), { c: 'whatever' }); +var combined = __assign(__assign({}, o), o2); +var combinedBefore = __assign(__assign({ b: 'ok' }, o), o2); +var combinedMid = __assign(__assign(__assign({}, o), { b: 'ok' }), o2); +var combinedAfter = __assign(__assign(__assign({}, o), o2), { b: 'ok' }); +var combinedNested = __assign(__assign(__assign({}, __assign({ a: 4 }, { b: false, c: 'overriden' })), { d: 'actually new' }), { a: 5, d: 'maybe new' }); +var combinedNestedChangeType = __assign(__assign({}, __assign({ a: 1 }, { b: false, c: 'overriden' })), { c: -1 }); var propertyNested = { a: __assign({}, o) }; // accessors don't copy the descriptor // (which means that readonly getters become read/write properties) var op = { get a() { return 6; } }; -var getter = __assign({}, op, { c: 7 }); +var getter = __assign(__assign({}, op), { c: 7 }); getter.a = 12; // functions result in { } var spreadFunc = __assign({}, (function () { })); function from16326(header, authToken) { - return __assign({}, this.header, header, authToken && { authToken: authToken }); + return __assign(__assign(__assign({}, this.header), header), authToken && { authToken: authToken }); } // boolean && T results in Partial function conditionalSpreadBoolean(b) { var o = { x: 12, y: 13 }; - o = __assign({}, o, b && { x: 14 }); + o = __assign(__assign({}, o), b && { x: 14 }); var o2 = __assign({}, b && { x: 21 }); return o; } function conditionalSpreadNumber(nt) { var o = { x: 15, y: 16 }; - o = __assign({}, o, nt && { x: nt }); + o = __assign(__assign({}, o), nt && { x: nt }); var o2 = __assign({}, nt && { x: nt }); return o; } function conditionalSpreadString(st) { var o = { x: 'hi', y: 17 }; - o = __assign({}, o, st && { x: st }); + o = __assign(__assign({}, o), st && { x: st }); var o2 = __assign({}, st && { x: st }); return o; } @@ -227,31 +227,31 @@ var C = /** @class */ (function () { var c = new C(); var spreadC = __assign({}, c); // own methods are enumerable -var cplus = __assign({}, c, { plus: function () { return this.p + 1; } }); +var cplus = __assign(__assign({}, c), { plus: function () { return this.p + 1; } }); cplus.plus(); // new field's type conflicting with existing field is OK -var changeTypeAfter = __assign({}, o, { a: 'wrong type?' }); +var changeTypeAfter = __assign(__assign({}, o), { a: 'wrong type?' }); var changeTypeBefore = __assign({ a: 'wrong type?' }, o); -var changeTypeBoth = __assign({}, o, swap); +var changeTypeBoth = __assign(__assign({}, o), swap); // optional function container(definiteBoolean, definiteString, optionalString, optionalNumber) { var _a, _b, _c; - var optionalUnionStops = __assign({}, definiteBoolean, definiteString, optionalNumber); - var optionalUnionDuplicates = __assign({}, definiteBoolean, definiteString, optionalString, optionalNumber); - var allOptional = __assign({}, optionalString, optionalNumber); + var optionalUnionStops = __assign(__assign(__assign({}, definiteBoolean), definiteString), optionalNumber); + var optionalUnionDuplicates = __assign(__assign(__assign(__assign({}, definiteBoolean), definiteString), optionalString), optionalNumber); + var allOptional = __assign(__assign({}, optionalString), optionalNumber); // computed property - var computedFirst = __assign((_a = {}, _a['before everything'] = 12, _a), o, { b: 'yes' }); - var computedMiddle = __assign({}, o, (_b = {}, _b['in the middle'] = 13, _b.b = 'maybe?', _b), o2); - var computedAfter = __assign({}, o, (_c = { b: 'yeah' }, _c['at the end'] = 14, _c)); + var computedFirst = __assign(__assign((_a = {}, _a['before everything'] = 12, _a), o), { b: 'yes' }); + var computedMiddle = __assign(__assign(__assign({}, o), (_b = {}, _b['in the middle'] = 13, _b.b = 'maybe?', _b)), o2); + var computedAfter = __assign(__assign({}, o), (_c = { b: 'yeah' }, _c['at the end'] = 14, _c)); } // shortcut syntax var a = 12; -var shortCutted = __assign({}, o, { a: a }); +var shortCutted = __assign(__assign({}, o), { a: a }); // non primitive var spreadNonPrimitive = __assign({}, {}); // generic spreads function f(t, u) { - return __assign({}, t, u, { id: 'id' }); + return __assign(__assign(__assign({}, t), u), { id: 'id' }); } var exclusive = f({ a: 1, b: 'yes' }, { c: 'no', d: false }); var overlap = f({ a: 1 }, { a: 2, b: 'extra' }); @@ -259,20 +259,20 @@ var overlapConflict = f({ a: 1 }, { a: 'mismatch' }); var overwriteId = f({ a: 1, id: true }, { c: 1, d: 'no' }); function genericSpread(t, u, v, w, obj) { var x01 = __assign({}, t); - var x02 = __assign({}, t, t); - var x03 = __assign({}, t, u); - var x04 = __assign({}, u, t); + var x02 = __assign(__assign({}, t), t); + var x03 = __assign(__assign({}, t), u); + var x04 = __assign(__assign({}, u), t); var x05 = __assign({ a: 5, b: 'hi' }, t); - var x06 = __assign({}, t, { a: 5, b: 'hi' }); - var x07 = __assign({ a: 5, b: 'hi' }, t, { c: true }, obj); - var x09 = __assign({ a: 5 }, t, { b: 'hi', c: true }, obj); - var x10 = __assign({ a: 5 }, t, { b: 'hi' }, u, obj); + var x06 = __assign(__assign({}, t), { a: 5, b: 'hi' }); + var x07 = __assign(__assign(__assign({ a: 5, b: 'hi' }, t), { c: true }), obj); + var x09 = __assign(__assign(__assign({ a: 5 }, t), { b: 'hi', c: true }), obj); + var x10 = __assign(__assign(__assign(__assign({ a: 5 }, t), { b: 'hi' }), u), obj); var x11 = __assign({}, v); - var x12 = __assign({}, v, obj); + var x12 = __assign(__assign({}, v), obj); var x13 = __assign({}, w); - var x14 = __assign({}, w, obj); - var x15 = __assign({}, t, v); - var x16 = __assign({}, t, w); - var x17 = __assign({}, t, w, obj); - var x18 = __assign({}, t, v, w); + var x14 = __assign(__assign({}, w), obj); + var x15 = __assign(__assign({}, t), v); + var x16 = __assign(__assign({}, t), w); + var x17 = __assign(__assign(__assign({}, t), w), obj); + var x18 = __assign(__assign(__assign({}, t), v), w); } diff --git a/tests/baselines/reference/objectSpreadComputedProperty.js b/tests/baselines/reference/objectSpreadComputedProperty.js index b81b889b2cc..a28ceab111f 100644 --- a/tests/baselines/reference/objectSpreadComputedProperty.js +++ b/tests/baselines/reference/objectSpreadComputedProperty.js @@ -30,5 +30,5 @@ function f() { var a = null; var o1 = __assign({}, (_a = {}, _a[n] = n, _a)); var o2 = __assign({}, (_b = {}, _b[a] = n, _b)); - var o3 = __assign((_c = {}, _c[a] = n, _c), {}, (_d = {}, _d[n] = n, _d), {}, (_e = {}, _e[m] = m, _e)); + var o3 = __assign(__assign(__assign(__assign((_c = {}, _c[a] = n, _c), {}), (_d = {}, _d[n] = n, _d)), {}), (_e = {}, _e[m] = m, _e)); } diff --git a/tests/baselines/reference/objectSpreadIndexSignature.js b/tests/baselines/reference/objectSpreadIndexSignature.js index aef78611f38..8c461e39971 100644 --- a/tests/baselines/reference/objectSpreadIndexSignature.js +++ b/tests/baselines/reference/objectSpreadIndexSignature.js @@ -30,10 +30,10 @@ var __assign = (this && this.__assign) || function () { }; return __assign.apply(this, arguments); }; -var i = __assign({}, indexed1, { b: 11 }); +var i = __assign(__assign({}, indexed1), { b: 11 }); // only indexed has indexer, so i[101]: any i[101]; -var ii = __assign({}, indexed1, indexed2); +var ii = __assign(__assign({}, indexed1), indexed2); // both have indexer, so i[1001]: number | boolean ii[1001]; indexed3 = __assign({}, b ? indexed3 : undefined); diff --git a/tests/baselines/reference/objectSpreadNegative.js b/tests/baselines/reference/objectSpreadNegative.js index 23de5699ce6..6151f2d30b7 100644 --- a/tests/baselines/reference/objectSpreadNegative.js +++ b/tests/baselines/reference/objectSpreadNegative.js @@ -85,11 +85,11 @@ var PublicX = /** @class */ (function () { }()); var publicX; var privateOptionalX; -var o2 = __assign({}, publicX, privateOptionalX); +var o2 = __assign(__assign({}, publicX), privateOptionalX); var sn = o2.x; // error, x is private var optionalString; var optionalNumber; -var allOptional = __assign({}, optionalString, optionalNumber); +var allOptional = __assign(__assign({}, optionalString), optionalNumber); ; ; var spread = __assign({ b: true }, { s: "foo" }); @@ -97,8 +97,8 @@ spread = { s: "foo" }; // error, missing 'b' var b = { b: false }; spread = b; // error, missing 's' // literal repeats are not allowed, but spread repeats are fine -var duplicated = __assign({ b: 'bad' }, o, { b: 'bad' }, o2, { b: 'bad' }); -var duplicatedSpread = __assign({}, o, o); +var duplicated = __assign(__assign(__assign(__assign({ b: 'bad' }, o), { b: 'bad' }), o2), { b: 'bad' }); +var duplicatedSpread = __assign(__assign({}, o), o); // primitives are not allowed, except for falsy ones var spreadNum = __assign({}, 12); var spreadSum = __assign({}, 1 + 1); diff --git a/tests/baselines/reference/objectSpreadNegativeParse.js b/tests/baselines/reference/objectSpreadNegativeParse.js index 1eb384383fb..11809b96b92 100644 --- a/tests/baselines/reference/objectSpreadNegativeParse.js +++ b/tests/baselines/reference/objectSpreadNegativeParse.js @@ -21,4 +21,4 @@ var o7 = __assign({}, o ? : ); var o8 = __assign({}, * o); var o9 = __assign({}, matchMedia()), _a = void 0; ; -var o10 = __assign({}, get, { x: function () { return 12; } }); +var o10 = __assign(__assign({}, get), { x: function () { return 12; } }); diff --git a/tests/baselines/reference/objectSpreadStrictNull.js b/tests/baselines/reference/objectSpreadStrictNull.js index 737c1d3e038..f95c2582b26 100644 --- a/tests/baselines/reference/objectSpreadStrictNull.js +++ b/tests/baselines/reference/objectSpreadStrictNull.js @@ -58,21 +58,21 @@ var __assign = (this && this.__assign) || function () { }; function f(definiteBoolean, definiteString, optionalString, optionalNumber, undefinedString, undefinedNumber) { // optional - var optionalUnionStops = __assign({}, definiteBoolean, definiteString, optionalNumber); - var optionalUnionDuplicates = __assign({}, definiteBoolean, definiteString, optionalString, optionalNumber); - var allOptional = __assign({}, optionalString, optionalNumber); + var optionalUnionStops = __assign(__assign(__assign({}, definiteBoolean), definiteString), optionalNumber); + var optionalUnionDuplicates = __assign(__assign(__assign(__assign({}, definiteBoolean), definiteString), optionalString), optionalNumber); + var allOptional = __assign(__assign({}, optionalString), optionalNumber); // undefined - var undefinedUnionStops = __assign({}, definiteBoolean, definiteString, undefinedNumber); - var undefinedUnionDuplicates = __assign({}, definiteBoolean, definiteString, undefinedString, undefinedNumber); - var allUndefined = __assign({}, undefinedString, undefinedNumber); - var undefinedWithOptionalContinues = __assign({}, definiteBoolean, undefinedString, optionalNumber); + var undefinedUnionStops = __assign(__assign(__assign({}, definiteBoolean), definiteString), undefinedNumber); + var undefinedUnionDuplicates = __assign(__assign(__assign(__assign({}, definiteBoolean), definiteString), undefinedString), undefinedNumber); + var allUndefined = __assign(__assign({}, undefinedString), undefinedNumber); + var undefinedWithOptionalContinues = __assign(__assign(__assign({}, definiteBoolean), undefinedString), optionalNumber); } var m = { title: "The Matrix", yearReleased: 1999 }; // should error here because title: undefined is not assignable to string -var x = __assign({}, m, { title: undefined }); +var x = __assign(__assign({}, m), { title: undefined }); function g(fields, partialFields, nearlyPartialFields) { // ok, undefined is stripped from optional properties when spread - fields = __assign({}, fields, partialFields); + fields = __assign(__assign({}, fields), partialFields); // error: not optional, undefined remains - fields = __assign({}, fields, nearlyPartialFields); + fields = __assign(__assign({}, fields), nearlyPartialFields); } diff --git a/tests/baselines/reference/objectSpreadWithinMethodWithinObjectWithSpread.js b/tests/baselines/reference/objectSpreadWithinMethodWithinObjectWithSpread.js index 89744f9f8e5..900dd89a820 100644 --- a/tests/baselines/reference/objectSpreadWithinMethodWithinObjectWithSpread.js +++ b/tests/baselines/reference/objectSpreadWithinMethodWithinObjectWithSpread.js @@ -24,6 +24,6 @@ var __assign = (this && this.__assign) || function () { return __assign.apply(this, arguments); }; var obj = {}; -var a = __assign({}, obj, { prop: function () { - return __assign({}, obj, { metadata: 213 }); +var a = __assign(__assign({}, obj), { prop: function () { + return __assign(__assign({}, obj), { metadata: 213 }); } }); diff --git a/tests/baselines/reference/spreadContextualTypedBindingPattern.js b/tests/baselines/reference/spreadContextualTypedBindingPattern.js index 7b2128e4a53..c95cccedbf3 100644 --- a/tests/baselines/reference/spreadContextualTypedBindingPattern.js +++ b/tests/baselines/reference/spreadContextualTypedBindingPattern.js @@ -25,4 +25,4 @@ var __assign = (this && this.__assign) || function () { return __assign.apply(this, arguments); }; // [ts] Initializer provides no value for this binding element and the binding element has no default value. -var _a = __assign({}, bob, alice), naam = _a.naam, age = _a.age; +var _a = __assign(__assign({}, bob), alice), naam = _a.naam, age = _a.age; diff --git a/tests/baselines/reference/spreadIntersection.js b/tests/baselines/reference/spreadIntersection.js index 2defebc5ce1..fe746734d6d 100644 --- a/tests/baselines/reference/spreadIntersection.js +++ b/tests/baselines/reference/spreadIntersection.js @@ -23,4 +23,4 @@ var intersection; var o1; var o1 = __assign({}, intersection); var o2; -var o2 = __assign({}, intersection, { c: false }); +var o2 = __assign(__assign({}, intersection), { c: false }); diff --git a/tests/baselines/reference/spreadNonPrimitive.js b/tests/baselines/reference/spreadNonPrimitive.js index 81b23a584fa..50b2c1cdec8 100644 --- a/tests/baselines/reference/spreadNonPrimitive.js +++ b/tests/baselines/reference/spreadNonPrimitive.js @@ -15,4 +15,4 @@ var __assign = (this && this.__assign) || function () { }; return __assign.apply(this, arguments); }; -var x = __assign({ a: 1 }, o, { b: 2 }); +var x = __assign(__assign({ a: 1 }, o), { b: 2 }); diff --git a/tests/baselines/reference/spreadUnion.js b/tests/baselines/reference/spreadUnion.js index 42ec336c67d..03220cef0e8 100644 --- a/tests/baselines/reference/spreadUnion.js +++ b/tests/baselines/reference/spreadUnion.js @@ -26,6 +26,6 @@ var union; var o3; var o3 = __assign({}, union); var o4; -var o4 = __assign({}, union, { a: false }); +var o4 = __assign(__assign({}, union), { a: false }); var o5; -var o5 = __assign({}, union, union); +var o5 = __assign(__assign({}, union), union); diff --git a/tests/baselines/reference/spreadUnion2.js b/tests/baselines/reference/spreadUnion2.js index 2678ce707cf..b48209cfc01 100644 --- a/tests/baselines/reference/spreadUnion2.js +++ b/tests/baselines/reference/spreadUnion2.js @@ -37,9 +37,9 @@ var o1 = __assign({}, undefinedUnion); var o2; var o2 = __assign({}, nullUnion); var o3; -var o3 = __assign({}, undefinedUnion, nullUnion); -var o3 = __assign({}, nullUnion, undefinedUnion); +var o3 = __assign(__assign({}, undefinedUnion), nullUnion); +var o3 = __assign(__assign({}, nullUnion), undefinedUnion); var o4; -var o4 = __assign({}, undefinedUnion, undefinedUnion); +var o4 = __assign(__assign({}, undefinedUnion), undefinedUnion); var o5; -var o5 = __assign({}, nullUnion, nullUnion); +var o5 = __assign(__assign({}, nullUnion), nullUnion); diff --git a/tests/baselines/reference/spreadUnion3.js b/tests/baselines/reference/spreadUnion3.js index 2175889db70..dda735a2dc1 100644 --- a/tests/baselines/reference/spreadUnion3.js +++ b/tests/baselines/reference/spreadUnion3.js @@ -42,5 +42,5 @@ function g(t) { g(); g(undefined); g(null); -var x = __assign({}, nullAndUndefinedUnion, nullAndUndefinedUnion); +var x = __assign(__assign({}, nullAndUndefinedUnion), nullAndUndefinedUnion); var y = __assign({}, nullAndUndefinedUnion); diff --git a/tests/baselines/reference/unionExcessPropsWithPartialMember.js b/tests/baselines/reference/unionExcessPropsWithPartialMember.js index cefd480bba8..f7e88d35a41 100644 --- a/tests/baselines/reference/unionExcessPropsWithPartialMember.js +++ b/tests/baselines/reference/unionExcessPropsWithPartialMember.js @@ -28,4 +28,4 @@ var __assign = (this && this.__assign) || function () { }; return __assign.apply(this, arguments); }; -ab = __assign({}, a, { y: null }); // Should be allowed, since `y` is missing on `A` +ab = __assign(__assign({}, a), { y: null }); // Should be allowed, since `y` is missing on `A` diff --git a/tests/baselines/reference/unknownType1.js b/tests/baselines/reference/unknownType1.js index 688fbf8f93c..8bd340de020 100644 --- a/tests/baselines/reference/unknownType1.js +++ b/tests/baselines/reference/unknownType1.js @@ -279,8 +279,8 @@ function f25() { // Spread of unknown causes result to be unknown function f26(x, y, z) { var o1 = __assign({ a: 42 }, x); // { a: number } - var o2 = __assign({ a: 42 }, x, y); // unknown - var o3 = __assign({ a: 42 }, x, y, z); // any + var o2 = __assign(__assign({ a: 42 }, x), y); // unknown + var o3 = __assign(__assign(__assign({ a: 42 }, x), y), z); // any } // Functions with unknown return type don't need return expressions function f27() { diff --git a/tests/baselines/reference/useBeforeDeclaration_propertyAssignment.js b/tests/baselines/reference/useBeforeDeclaration_propertyAssignment.js index 47968d429ad..4ee81065518 100644 --- a/tests/baselines/reference/useBeforeDeclaration_propertyAssignment.js +++ b/tests/baselines/reference/useBeforeDeclaration_propertyAssignment.js @@ -20,7 +20,7 @@ class D { //// [useBeforeDeclaration_propertyAssignment.js] export class C { constructor() { - this.a = Object.assign({ b: this.b }, this.c, { [this.b]: `${this.c}` }); + this.a = Object.assign(Object.assign({ b: this.b }, this.c), { [this.b]: `${this.c}` }); this.b = 0; this.c = { c: this.b }; } From d982014d733445f478b5cad8a938d2d2a56f1080 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 22 Jul 2019 17:23:35 -0700 Subject: [PATCH 043/151] Update __awaiter to be more spec compliant (#32462) * Update __awaiter to be more spec compliant * Add awaiter evaluation test --- src/compiler/transformers/es2017.ts | 3 ++- src/testRunner/tsconfig.json | 1 + .../unittests/evaluation/awaiter.ts | 24 +++++++++++++++++++ .../reference/asyncArrowFunction11_es5.js | 3 ++- .../asyncAwaitIsolatedModules_es5.js | 3 ++- .../asyncAwaitIsolatedModules_es6.js | 3 ++- tests/baselines/reference/asyncAwait_es5.js | 3 ++- tests/baselines/reference/asyncAwait_es6.js | 3 ++- .../reference/asyncFunctionNoReturnType.js | 3 ++- ...asyncFunctionReturnExpressionErrorSpans.js | 3 ++- .../reference/asyncFunctionReturnType.js | 3 ++- .../asyncFunctionTempVariableScoping.js | 3 ++- ...ncFunctionWithForStatementNoInitializer.js | 3 ++- .../reference/asyncFunctionsAcrossFiles.js | 6 +++-- .../asyncFunctionsAndStrictNullChecks.js | 3 ++- tests/baselines/reference/asyncIIFE.js | 3 ++- .../reference/asyncImportedPromise_es5.js | 3 ++- .../reference/asyncImportedPromise_es6.js | 3 ++- .../asyncMethodWithSuperConflict_es6.js | 3 ++- .../baselines/reference/asyncMultiFile_es5.js | 3 ++- .../baselines/reference/asyncMultiFile_es6.js | 3 ++- .../baselines/reference/awaitUnionPromise.js | 3 ++- .../reference/await_unaryExpression_es6.js | 3 ++- .../reference/await_unaryExpression_es6_1.js | 3 ++- .../reference/await_unaryExpression_es6_2.js | 3 ++- .../reference/await_unaryExpression_es6_3.js | 3 ++- .../capturedParametersInInitializers1.js | 3 ++- tests/baselines/reference/castOfAwait.js | 3 ++- .../checkJsxSubtleSkipContextSensitiveBug.js | 3 ++- .../circularInferredTypeOfVariable.js | 3 ++- .../controlFlowForCatchAndFinally.js | 3 ++- .../reference/correctOrderOfPromiseMethod.js | 3 ++- .../reference/declarationEmitPrivateAsync.js | 3 ++- .../reference/declarationEmitPromise.js | 3 ++- .../reference/decoratorMetadataPromise.js | 3 ++- .../defaultExportInAwaitExpression01.js | 3 ++- .../defaultExportInAwaitExpression02.js | 3 ++- .../reference/emitter.forAwait.es2015.js | 9 ++++--- .../reference/emitter.forAwait.es5.js | 9 ++++--- .../baselines/reference/es5-asyncFunction.js | 3 ++- .../es5-importHelpersAsyncFunctions.js | 3 ++- .../reference/exportDefaultAsyncFunction.js | 3 ++- .../reference/exportDefaultAsyncFunction2.js | 3 ++- .../exportDefaultFunctionInNamespace.js | 3 ++- ...essionsForbiddenInParameterInitializers.js | 3 ++- .../importCallExpressionAsyncES3AMD.js | 3 ++- .../importCallExpressionAsyncES3CJS.js | 3 ++- .../importCallExpressionAsyncES3System.js | 3 ++- .../importCallExpressionAsyncES3UMD.js | 3 ++- .../importCallExpressionAsyncES5AMD.js | 3 ++- .../importCallExpressionAsyncES5CJS.js | 3 ++- .../importCallExpressionAsyncES5System.js | 3 ++- .../importCallExpressionAsyncES5UMD.js | 3 ++- .../importCallExpressionAsyncES6AMD.js | 3 ++- .../importCallExpressionAsyncES6CJS.js | 3 ++- .../importCallExpressionAsyncES6System.js | 3 ++- .../importCallExpressionAsyncES6UMD.js | 3 ++- .../importCallExpressionNestedAMD.js | 3 ++- .../importCallExpressionNestedAMD2.js | 3 ++- .../importCallExpressionNestedCJS.js | 3 ++- .../importCallExpressionNestedCJS2.js | 3 ++- .../importCallExpressionNestedES2015.js | 3 ++- .../importCallExpressionNestedES20152.js | 3 ++- .../importCallExpressionNestedESNext.js | 3 ++- .../importCallExpressionNestedESNext2.js | 3 ++- .../importCallExpressionNestedSystem.js | 3 ++- .../importCallExpressionNestedSystem2.js | 3 ++- .../importCallExpressionNestedUMD.js | 3 ++- .../importCallExpressionNestedUMD2.js | 3 ++- ...portCallExpressionNoModuleKindSpecified.js | 3 ++- tests/baselines/reference/importMetaES5.js | 3 ++- tests/baselines/reference/inferenceLimit.js | 3 ++- .../invalidContinueInDownlevelAsync.js | 3 ++- .../reference/labeledStatementWithLabel.js | 3 ++- .../labeledStatementWithLabel_es2015.js | 3 ++- .../labeledStatementWithLabel_strict.js | 3 ++- ...rizeLibrary_NoErrorDuplicateLibOptions1.js | 3 ++- ...rizeLibrary_NoErrorDuplicateLibOptions2.js | 3 ++- .../modularizeLibrary_TargetES5UsingES6Lib.js | 3 ++- .../reference/noImplicitReturnsInAsync1.js | 3 ++- .../reference/noImplicitReturnsInAsync2.js | 3 ++- tests/baselines/reference/objectRest2.js | 3 ++- .../operationsAvailableOnPromisedType.js | 3 ++- .../parenthesizedAsyncArrowFunction.js | 3 ++- .../reference/promiseDefinitionTest.js | 3 ++- tests/baselines/reference/promiseType.js | 3 ++- .../reference/promiseTypeStrictNull.js | 3 ++- .../reference/reachabilityChecks7.js | 3 ++- ...uxLikeDeferredInferenceAllowsAssignment.js | 3 ++- .../reference/thisTypeInFunctionsNegative.js | 3 ++- .../transformNestedGeneratorsWithTry.js | 3 ++- 91 files changed, 213 insertions(+), 94 deletions(-) create mode 100644 src/testRunner/unittests/evaluation/awaiter.ts diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 8d20f94afed..9c2d5700d43 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -775,10 +775,11 @@ namespace ts { priority: 5, text: ` var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); };` diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 9ea6c4c85ce..659dd426b79 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -73,6 +73,7 @@ "unittests/config/tsconfigParsing.ts", "unittests/evaluation/asyncArrow.ts", "unittests/evaluation/asyncGenerator.ts", + "unittests/evaluation/awaiter.ts", "unittests/evaluation/forAwaitOf.ts", "unittests/evaluation/objectRest.ts", "unittests/services/cancellableLanguageServiceOperations.ts", diff --git a/src/testRunner/unittests/evaluation/awaiter.ts b/src/testRunner/unittests/evaluation/awaiter.ts new file mode 100644 index 00000000000..65cb4e0ead9 --- /dev/null +++ b/src/testRunner/unittests/evaluation/awaiter.ts @@ -0,0 +1,24 @@ +describe("unittests:: evaluation:: awaiter", () => { + // NOTE: This could break if the ECMAScript spec ever changes the timing behavior for Promises (again) + it("await (es5)", async () => { + const result = evaluator.evaluateTypeScript(` + async function a(msg: string) { + await Promise.resolve(); + output.push(msg); + } + function b(msg: string) { + return Promise.resolve().then(() => { + output.push(msg); + }); + } + export const output: string[] = []; + export async function main() { + const p1 = a('1'); + const p2 = b('2'); + await Promise.all([p1, p2]); + } + `); + await result.main(); + assert.deepEqual(result.output, ["1", "2"]); + }); +}); diff --git a/tests/baselines/reference/asyncArrowFunction11_es5.js b/tests/baselines/reference/asyncArrowFunction11_es5.js index 5f234f2fbf6..a16ce36e840 100644 --- a/tests/baselines/reference/asyncArrowFunction11_es5.js +++ b/tests/baselines/reference/asyncArrowFunction11_es5.js @@ -9,10 +9,11 @@ class A { //// [asyncArrowFunction11_es5.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js b/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js index 58b887c61a3..934f6be814a 100644 --- a/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es5.js @@ -42,10 +42,11 @@ module M { //// [asyncAwaitIsolatedModules_es5.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js b/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js index 046b74e6569..2b956515ba1 100644 --- a/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es6.js @@ -41,10 +41,11 @@ module M { //// [asyncAwaitIsolatedModules_es6.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncAwait_es5.js b/tests/baselines/reference/asyncAwait_es5.js index ee8f160b2a4..6a6433e85c6 100644 --- a/tests/baselines/reference/asyncAwait_es5.js +++ b/tests/baselines/reference/asyncAwait_es5.js @@ -48,10 +48,11 @@ async function f14() { //// [asyncAwait_es5.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncAwait_es6.js b/tests/baselines/reference/asyncAwait_es6.js index 3cfe3b3ceec..caab72bad9a 100644 --- a/tests/baselines/reference/asyncAwait_es6.js +++ b/tests/baselines/reference/asyncAwait_es6.js @@ -48,10 +48,11 @@ async function f14() { //// [asyncAwait_es6.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncFunctionNoReturnType.js b/tests/baselines/reference/asyncFunctionNoReturnType.js index b376e398d17..430210cbdbc 100644 --- a/tests/baselines/reference/asyncFunctionNoReturnType.js +++ b/tests/baselines/reference/asyncFunctionNoReturnType.js @@ -7,10 +7,11 @@ async () => { //// [asyncFunctionNoReturnType.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.js b/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.js index d60a7df66d0..887484e933a 100644 --- a/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.js +++ b/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.js @@ -23,10 +23,11 @@ async function asyncFoo(): Promise { //// [asyncFunctionReturnExpressionErrorSpans.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncFunctionReturnType.js b/tests/baselines/reference/asyncFunctionReturnType.js index 6e39e72ae4c..04b3a04a036 100644 --- a/tests/baselines/reference/asyncFunctionReturnType.js +++ b/tests/baselines/reference/asyncFunctionReturnType.js @@ -77,10 +77,11 @@ async function fGenericIndexedTypeForExplicitPromiseOfKProp bar(await foo); //// [asyncFunctionTempVariableScoping.js] // https://github.com/Microsoft/TypeScript/issues/19187 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncFunctionWithForStatementNoInitializer.js b/tests/baselines/reference/asyncFunctionWithForStatementNoInitializer.js index 99394281a15..055a751f523 100644 --- a/tests/baselines/reference/asyncFunctionWithForStatementNoInitializer.js +++ b/tests/baselines/reference/asyncFunctionWithForStatementNoInitializer.js @@ -26,10 +26,11 @@ async function test4() { //// [asyncFunctionWithForStatementNoInitializer.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncFunctionsAcrossFiles.js b/tests/baselines/reference/asyncFunctionsAcrossFiles.js index b1a766e4e41..cd86f20c69d 100644 --- a/tests/baselines/reference/asyncFunctionsAcrossFiles.js +++ b/tests/baselines/reference/asyncFunctionsAcrossFiles.js @@ -17,10 +17,11 @@ export const b = { //// [b.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; @@ -32,10 +33,11 @@ export const b = { }; //// [a.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js b/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js index 2afcf5d7dfd..a13f2f8b219 100644 --- a/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js +++ b/tests/baselines/reference/asyncFunctionsAndStrictNullChecks.js @@ -27,10 +27,11 @@ async function sample2(x?: number) { //// [asyncFunctionsAndStrictNullChecks.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncIIFE.js b/tests/baselines/reference/asyncIIFE.js index 8ca87781113..e2096b4c6de 100644 --- a/tests/baselines/reference/asyncIIFE.js +++ b/tests/baselines/reference/asyncIIFE.js @@ -11,10 +11,11 @@ function f1() { //// [asyncIIFE.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncImportedPromise_es5.js b/tests/baselines/reference/asyncImportedPromise_es5.js index f17459321c8..11699f6ab1e 100644 --- a/tests/baselines/reference/asyncImportedPromise_es5.js +++ b/tests/baselines/reference/asyncImportedPromise_es5.js @@ -36,10 +36,11 @@ exports.Task = Task; //// [test.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncImportedPromise_es6.js b/tests/baselines/reference/asyncImportedPromise_es6.js index 6b84f5615b3..41bf0f26087 100644 --- a/tests/baselines/reference/asyncImportedPromise_es6.js +++ b/tests/baselines/reference/asyncImportedPromise_es6.js @@ -18,10 +18,11 @@ exports.Task = Task; //// [test.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js index 2a910226703..5e2a152b9e0 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js @@ -61,10 +61,11 @@ class B extends A { //// [asyncMethodWithSuperConflict_es6.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncMultiFile_es5.js b/tests/baselines/reference/asyncMultiFile_es5.js index a6dbb44ef9e..392a4456cc2 100644 --- a/tests/baselines/reference/asyncMultiFile_es5.js +++ b/tests/baselines/reference/asyncMultiFile_es5.js @@ -7,10 +7,11 @@ function g() { } //// [a.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/asyncMultiFile_es6.js b/tests/baselines/reference/asyncMultiFile_es6.js index e7dd854b95b..7fbb00063c7 100644 --- a/tests/baselines/reference/asyncMultiFile_es6.js +++ b/tests/baselines/reference/asyncMultiFile_es6.js @@ -7,10 +7,11 @@ function g() { } //// [a.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/awaitUnionPromise.js b/tests/baselines/reference/awaitUnionPromise.js index 90b894ee0f5..723339b9f71 100644 --- a/tests/baselines/reference/awaitUnionPromise.js +++ b/tests/baselines/reference/awaitUnionPromise.js @@ -23,10 +23,11 @@ async function main() { /// @target: es2015 // https://github.com/Microsoft/TypeScript/issues/18186 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/await_unaryExpression_es6.js b/tests/baselines/reference/await_unaryExpression_es6.js index 1361f80bc8e..69eef173613 100644 --- a/tests/baselines/reference/await_unaryExpression_es6.js +++ b/tests/baselines/reference/await_unaryExpression_es6.js @@ -17,10 +17,11 @@ async function bar4() { //// [await_unaryExpression_es6.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/await_unaryExpression_es6_1.js b/tests/baselines/reference/await_unaryExpression_es6_1.js index 297299e4462..3a205f05ea9 100644 --- a/tests/baselines/reference/await_unaryExpression_es6_1.js +++ b/tests/baselines/reference/await_unaryExpression_es6_1.js @@ -21,10 +21,11 @@ async function bar4() { //// [await_unaryExpression_es6_1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/await_unaryExpression_es6_2.js b/tests/baselines/reference/await_unaryExpression_es6_2.js index fdf83e3def1..ee59f5825ae 100644 --- a/tests/baselines/reference/await_unaryExpression_es6_2.js +++ b/tests/baselines/reference/await_unaryExpression_es6_2.js @@ -13,10 +13,11 @@ async function bar3() { //// [await_unaryExpression_es6_2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/await_unaryExpression_es6_3.js b/tests/baselines/reference/await_unaryExpression_es6_3.js index 23985832ce1..42643caa262 100644 --- a/tests/baselines/reference/await_unaryExpression_es6_3.js +++ b/tests/baselines/reference/await_unaryExpression_es6_3.js @@ -19,10 +19,11 @@ async function bar4() { //// [await_unaryExpression_es6_3.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/capturedParametersInInitializers1.js b/tests/baselines/reference/capturedParametersInInitializers1.js index 7ec393e2e39..ec5ff77d84b 100644 --- a/tests/baselines/reference/capturedParametersInInitializers1.js +++ b/tests/baselines/reference/capturedParametersInInitializers1.js @@ -42,10 +42,11 @@ function foo9(y = {[z]() { return z; }}, z = 1) { //// [capturedParametersInInitializers1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/castOfAwait.js b/tests/baselines/reference/castOfAwait.js index 9f67f74b11b..c00c1b028f4 100644 --- a/tests/baselines/reference/castOfAwait.js +++ b/tests/baselines/reference/castOfAwait.js @@ -10,10 +10,11 @@ async function f() { //// [castOfAwait.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js index 704781dbe58..d1d6dd7eeec 100644 --- a/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js +++ b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js @@ -40,10 +40,11 @@ var __extends = (this && this.__extends) || (function () { }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/circularInferredTypeOfVariable.js b/tests/baselines/reference/circularInferredTypeOfVariable.js index e7ba96ebaf8..d3e4dd0dc58 100644 --- a/tests/baselines/reference/circularInferredTypeOfVariable.js +++ b/tests/baselines/reference/circularInferredTypeOfVariable.js @@ -21,10 +21,11 @@ //// [circularInferredTypeOfVariable.js] // Repro from #14428 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/controlFlowForCatchAndFinally.js b/tests/baselines/reference/controlFlowForCatchAndFinally.js index b3dfc4e7bb8..48075ffb6b4 100644 --- a/tests/baselines/reference/controlFlowForCatchAndFinally.js +++ b/tests/baselines/reference/controlFlowForCatchAndFinally.js @@ -43,10 +43,11 @@ class Foo { //// [controlFlowForCatchAndFinally.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/correctOrderOfPromiseMethod.js b/tests/baselines/reference/correctOrderOfPromiseMethod.js index 4c273d3c0f2..58c98189a43 100644 --- a/tests/baselines/reference/correctOrderOfPromiseMethod.js +++ b/tests/baselines/reference/correctOrderOfPromiseMethod.js @@ -27,10 +27,11 @@ async function countEverything(): Promise { //// [correctOrderOfPromiseMethod.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/declarationEmitPrivateAsync.js b/tests/baselines/reference/declarationEmitPrivateAsync.js index deeb9fd15d9..89f33267b8a 100644 --- a/tests/baselines/reference/declarationEmitPrivateAsync.js +++ b/tests/baselines/reference/declarationEmitPrivateAsync.js @@ -8,10 +8,11 @@ export class Foo { //// [declarationEmitPrivateAsync.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/declarationEmitPromise.js b/tests/baselines/reference/declarationEmitPromise.js index 6822dc56c3d..313ffa04183 100644 --- a/tests/baselines/reference/declarationEmitPromise.js +++ b/tests/baselines/reference/declarationEmitPromise.js @@ -24,10 +24,11 @@ export async function runSampleBreaks( //// [declarationEmitPromise.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/decoratorMetadataPromise.js b/tests/baselines/reference/decoratorMetadataPromise.js index a370df936d5..41bb42e2732 100644 --- a/tests/baselines/reference/decoratorMetadataPromise.js +++ b/tests/baselines/reference/decoratorMetadataPromise.js @@ -22,10 +22,11 @@ var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/defaultExportInAwaitExpression01.js b/tests/baselines/reference/defaultExportInAwaitExpression01.js index 6a31461fe3c..950c1141136 100644 --- a/tests/baselines/reference/defaultExportInAwaitExpression01.js +++ b/tests/baselines/reference/defaultExportInAwaitExpression01.js @@ -29,10 +29,11 @@ import x from './a'; }); //// [b.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/defaultExportInAwaitExpression02.js b/tests/baselines/reference/defaultExportInAwaitExpression02.js index 565cfb41617..8aa41a6b52a 100644 --- a/tests/baselines/reference/defaultExportInAwaitExpression02.js +++ b/tests/baselines/reference/defaultExportInAwaitExpression02.js @@ -20,10 +20,11 @@ exports.default = x; //// [b.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/emitter.forAwait.es2015.js b/tests/baselines/reference/emitter.forAwait.es2015.js index e5764747765..2b2cc3ce08d 100644 --- a/tests/baselines/reference/emitter.forAwait.es2015.js +++ b/tests/baselines/reference/emitter.forAwait.es2015.js @@ -43,10 +43,11 @@ async function* f6() { //// [file1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; @@ -77,10 +78,11 @@ function f1() { } //// [file2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; @@ -187,10 +189,11 @@ function f4() { } //// [file5.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/emitter.forAwait.es5.js b/tests/baselines/reference/emitter.forAwait.es5.js index 0d67c591e30..f33af25dcc1 100644 --- a/tests/baselines/reference/emitter.forAwait.es5.js +++ b/tests/baselines/reference/emitter.forAwait.es5.js @@ -43,10 +43,11 @@ async function* f6() { //// [file1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; @@ -124,10 +125,11 @@ function f1() { } //// [file2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; @@ -375,10 +377,11 @@ function f4() { } //// [file5.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/es5-asyncFunction.js b/tests/baselines/reference/es5-asyncFunction.js index 9b5744be31e..805e4d4a4c7 100644 --- a/tests/baselines/reference/es5-asyncFunction.js +++ b/tests/baselines/reference/es5-asyncFunction.js @@ -10,10 +10,11 @@ async function singleAwait() { //// [es5-asyncFunction.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/es5-importHelpersAsyncFunctions.js b/tests/baselines/reference/es5-importHelpersAsyncFunctions.js index 932fd8185eb..75ac303d3c0 100644 --- a/tests/baselines/reference/es5-importHelpersAsyncFunctions.js +++ b/tests/baselines/reference/es5-importHelpersAsyncFunctions.js @@ -31,10 +31,11 @@ function foo() { exports.foo = foo; //// [script.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/exportDefaultAsyncFunction.js b/tests/baselines/reference/exportDefaultAsyncFunction.js index 9931d1f1eea..31460daae84 100644 --- a/tests/baselines/reference/exportDefaultAsyncFunction.js +++ b/tests/baselines/reference/exportDefaultAsyncFunction.js @@ -5,10 +5,11 @@ foo(); //// [exportDefaultAsyncFunction.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/exportDefaultAsyncFunction2.js b/tests/baselines/reference/exportDefaultAsyncFunction2.js index 8f889381140..ad9b9086a74 100644 --- a/tests/baselines/reference/exportDefaultAsyncFunction2.js +++ b/tests/baselines/reference/exportDefaultAsyncFunction2.js @@ -35,10 +35,11 @@ import { async, await } from 'asyncawait'; export default async(() => await(Promise.resolve(1))); //// [b.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/exportDefaultFunctionInNamespace.js b/tests/baselines/reference/exportDefaultFunctionInNamespace.js index 3a0c260ff01..482611413b7 100644 --- a/tests/baselines/reference/exportDefaultFunctionInNamespace.js +++ b/tests/baselines/reference/exportDefaultFunctionInNamespace.js @@ -10,10 +10,11 @@ namespace ns_async_function { //// [exportDefaultFunctionInNamespace.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/expressionsForbiddenInParameterInitializers.js b/tests/baselines/reference/expressionsForbiddenInParameterInitializers.js index e12f4b6a232..a23a820e8e5 100644 --- a/tests/baselines/reference/expressionsForbiddenInParameterInitializers.js +++ b/tests/baselines/reference/expressionsForbiddenInParameterInitializers.js @@ -9,10 +9,11 @@ export function* foo2({ foo = yield "a" }) { //// [bar.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES3AMD.js b/tests/baselines/reference/importCallExpressionAsyncES3AMD.js index 7a8776ebe10..9b4f7f76cc7 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES3AMD.js +++ b/tests/baselines/reference/importCallExpressionAsyncES3AMD.js @@ -30,10 +30,11 @@ export const l = async () => { //// [test.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES3CJS.js b/tests/baselines/reference/importCallExpressionAsyncES3CJS.js index ba16d3bbd27..43b4c868529 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES3CJS.js +++ b/tests/baselines/reference/importCallExpressionAsyncES3CJS.js @@ -31,10 +31,11 @@ export const l = async () => { //// [test.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES3System.js b/tests/baselines/reference/importCallExpressionAsyncES3System.js index f8b7e54e5cd..6369c73b68b 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES3System.js +++ b/tests/baselines/reference/importCallExpressionAsyncES3System.js @@ -32,10 +32,11 @@ export const l = async () => { System.register([], function (exports_1, context_1) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES3UMD.js b/tests/baselines/reference/importCallExpressionAsyncES3UMD.js index 0f13a0252a6..794678e871d 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES3UMD.js +++ b/tests/baselines/reference/importCallExpressionAsyncES3UMD.js @@ -30,10 +30,11 @@ export const l = async () => { //// [test.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES5AMD.js b/tests/baselines/reference/importCallExpressionAsyncES5AMD.js index 17ba4f7e8bf..2451190c793 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES5AMD.js +++ b/tests/baselines/reference/importCallExpressionAsyncES5AMD.js @@ -30,10 +30,11 @@ export const l = async () => { //// [test.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES5CJS.js b/tests/baselines/reference/importCallExpressionAsyncES5CJS.js index 8e00d5b9739..cd60c69c4cf 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES5CJS.js +++ b/tests/baselines/reference/importCallExpressionAsyncES5CJS.js @@ -31,10 +31,11 @@ export const l = async () => { //// [test.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES5System.js b/tests/baselines/reference/importCallExpressionAsyncES5System.js index f63d41bf9a5..da510e8d098 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES5System.js +++ b/tests/baselines/reference/importCallExpressionAsyncES5System.js @@ -32,10 +32,11 @@ export const l = async () => { System.register([], function (exports_1, context_1) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES5UMD.js b/tests/baselines/reference/importCallExpressionAsyncES5UMD.js index 1c8ecdc5118..111b747ff32 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES5UMD.js +++ b/tests/baselines/reference/importCallExpressionAsyncES5UMD.js @@ -30,10 +30,11 @@ export const l = async () => { //// [test.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES6AMD.js b/tests/baselines/reference/importCallExpressionAsyncES6AMD.js index 7f86625bbfc..80cf843ade9 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES6AMD.js +++ b/tests/baselines/reference/importCallExpressionAsyncES6AMD.js @@ -30,10 +30,11 @@ export const l = async () => { //// [test.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES6CJS.js b/tests/baselines/reference/importCallExpressionAsyncES6CJS.js index 20961f96330..7ce2b69b44c 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES6CJS.js +++ b/tests/baselines/reference/importCallExpressionAsyncES6CJS.js @@ -31,10 +31,11 @@ export const l = async () => { //// [test.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES6System.js b/tests/baselines/reference/importCallExpressionAsyncES6System.js index 1f605dcc3f8..8dd7e2f32e8 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES6System.js +++ b/tests/baselines/reference/importCallExpressionAsyncES6System.js @@ -32,10 +32,11 @@ export const l = async () => { System.register([], function (exports_1, context_1) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES6UMD.js b/tests/baselines/reference/importCallExpressionAsyncES6UMD.js index 1d4aff02670..f7dfe0d9934 100644 --- a/tests/baselines/reference/importCallExpressionAsyncES6UMD.js +++ b/tests/baselines/reference/importCallExpressionAsyncES6UMD.js @@ -30,10 +30,11 @@ export const l = async () => { //// [test.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedAMD.js b/tests/baselines/reference/importCallExpressionNestedAMD.js index dc211d44003..678c02a8e73 100644 --- a/tests/baselines/reference/importCallExpressionNestedAMD.js +++ b/tests/baselines/reference/importCallExpressionNestedAMD.js @@ -16,10 +16,11 @@ define(["require", "exports"], function (require, exports) { }); //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedAMD2.js b/tests/baselines/reference/importCallExpressionNestedAMD2.js index f6ebbe32c7b..ffc42963975 100644 --- a/tests/baselines/reference/importCallExpressionNestedAMD2.js +++ b/tests/baselines/reference/importCallExpressionNestedAMD2.js @@ -16,10 +16,11 @@ define(["require", "exports"], function (require, exports) { }); //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedCJS.js b/tests/baselines/reference/importCallExpressionNestedCJS.js index 07c0f234bf7..5b6abef5e0e 100644 --- a/tests/baselines/reference/importCallExpressionNestedCJS.js +++ b/tests/baselines/reference/importCallExpressionNestedCJS.js @@ -14,10 +14,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = "./foo"; //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedCJS2.js b/tests/baselines/reference/importCallExpressionNestedCJS2.js index 97728dfb41f..104a01b5bd9 100644 --- a/tests/baselines/reference/importCallExpressionNestedCJS2.js +++ b/tests/baselines/reference/importCallExpressionNestedCJS2.js @@ -14,10 +14,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = "./foo"; //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedES2015.js b/tests/baselines/reference/importCallExpressionNestedES2015.js index 5c8a6a9edb5..8bbb7c7b1f3 100644 --- a/tests/baselines/reference/importCallExpressionNestedES2015.js +++ b/tests/baselines/reference/importCallExpressionNestedES2015.js @@ -12,10 +12,11 @@ async function foo() { export default "./foo"; //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedES20152.js b/tests/baselines/reference/importCallExpressionNestedES20152.js index 0baee242a60..c0b888df2fb 100644 --- a/tests/baselines/reference/importCallExpressionNestedES20152.js +++ b/tests/baselines/reference/importCallExpressionNestedES20152.js @@ -12,10 +12,11 @@ async function foo() { export default "./foo"; //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedESNext.js b/tests/baselines/reference/importCallExpressionNestedESNext.js index 8ec9b988201..77ade8e8928 100644 --- a/tests/baselines/reference/importCallExpressionNestedESNext.js +++ b/tests/baselines/reference/importCallExpressionNestedESNext.js @@ -12,10 +12,11 @@ async function foo() { export default "./foo"; //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedESNext2.js b/tests/baselines/reference/importCallExpressionNestedESNext2.js index 07bfaf89d40..cfe3fca6aeb 100644 --- a/tests/baselines/reference/importCallExpressionNestedESNext2.js +++ b/tests/baselines/reference/importCallExpressionNestedESNext2.js @@ -12,10 +12,11 @@ async function foo() { export default "./foo"; //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedSystem.js b/tests/baselines/reference/importCallExpressionNestedSystem.js index 839a3601e38..15a825c8a76 100644 --- a/tests/baselines/reference/importCallExpressionNestedSystem.js +++ b/tests/baselines/reference/importCallExpressionNestedSystem.js @@ -22,10 +22,11 @@ System.register([], function (exports_1, context_1) { //// [index.js] System.register([], function (exports_1, context_1) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedSystem2.js b/tests/baselines/reference/importCallExpressionNestedSystem2.js index 1685ca93943..60861b7aca7 100644 --- a/tests/baselines/reference/importCallExpressionNestedSystem2.js +++ b/tests/baselines/reference/importCallExpressionNestedSystem2.js @@ -22,10 +22,11 @@ System.register([], function (exports_1, context_1) { //// [index.js] System.register([], function (exports_1, context_1) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedUMD.js b/tests/baselines/reference/importCallExpressionNestedUMD.js index c61e35c3399..29f0e0974ed 100644 --- a/tests/baselines/reference/importCallExpressionNestedUMD.js +++ b/tests/baselines/reference/importCallExpressionNestedUMD.js @@ -24,10 +24,11 @@ async function foo() { }); //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNestedUMD2.js b/tests/baselines/reference/importCallExpressionNestedUMD2.js index 5d1646d090a..33d3d608e14 100644 --- a/tests/baselines/reference/importCallExpressionNestedUMD2.js +++ b/tests/baselines/reference/importCallExpressionNestedUMD2.js @@ -24,10 +24,11 @@ async function foo() { }); //// [index.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js b/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js index 4f662c4be4f..9c54007d33f 100644 --- a/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js +++ b/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js @@ -45,10 +45,11 @@ function backup() { return "backup"; } exports.backup = backup; //// [2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/importMetaES5.js b/tests/baselines/reference/importMetaES5.js index e618f695869..6b69557e419 100644 --- a/tests/baselines/reference/importMetaES5.js +++ b/tests/baselines/reference/importMetaES5.js @@ -41,10 +41,11 @@ const { a, b, c } = import.meta.wellKnownProperty; //// [example.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/inferenceLimit.js b/tests/baselines/reference/inferenceLimit.js index 997cbcd5b79..e27d155d616 100644 --- a/tests/baselines/reference/inferenceLimit.js +++ b/tests/baselines/reference/inferenceLimit.js @@ -46,10 +46,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); //// [file1.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/invalidContinueInDownlevelAsync.js b/tests/baselines/reference/invalidContinueInDownlevelAsync.js index 793a9451f87..9a2fc08f4a8 100644 --- a/tests/baselines/reference/invalidContinueInDownlevelAsync.js +++ b/tests/baselines/reference/invalidContinueInDownlevelAsync.js @@ -10,10 +10,11 @@ async function func() { //// [invalidContinueInDownlevelAsync.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/labeledStatementWithLabel.js b/tests/baselines/reference/labeledStatementWithLabel.js index ada819c9908..92c0472c222 100644 --- a/tests/baselines/reference/labeledStatementWithLabel.js +++ b/tests/baselines/reference/labeledStatementWithLabel.js @@ -16,10 +16,11 @@ label: type T = {} //// [labeledStatementWithLabel.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/labeledStatementWithLabel_es2015.js b/tests/baselines/reference/labeledStatementWithLabel_es2015.js index 34ceb7bc17a..93d76684c6d 100644 --- a/tests/baselines/reference/labeledStatementWithLabel_es2015.js +++ b/tests/baselines/reference/labeledStatementWithLabel_es2015.js @@ -16,10 +16,11 @@ label: type T = {} //// [labeledStatementWithLabel_es2015.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/labeledStatementWithLabel_strict.js b/tests/baselines/reference/labeledStatementWithLabel_strict.js index bcf211fdbfd..124c6c0bde2 100644 --- a/tests/baselines/reference/labeledStatementWithLabel_strict.js +++ b/tests/baselines/reference/labeledStatementWithLabel_strict.js @@ -18,10 +18,11 @@ label: type T = {} //// [labeledStatementWithLabel_strict.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js index 8fdb55a0f26..5c16fa2a389 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.js @@ -82,10 +82,11 @@ const o1 = { //// [modularizeLibrary_NoErrorDuplicateLibOptions1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js index 21a8fa48b1f..9d340096491 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.js @@ -82,10 +82,11 @@ const o1 = { //// [modularizeLibrary_NoErrorDuplicateLibOptions2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js index 093f3bde868..57fca626c06 100644 --- a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js +++ b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.js @@ -82,10 +82,11 @@ const o1 = { //// [modularizeLibrary_TargetES5UsingES6Lib.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/noImplicitReturnsInAsync1.js b/tests/baselines/reference/noImplicitReturnsInAsync1.js index e165cafe3b1..d803694056f 100644 --- a/tests/baselines/reference/noImplicitReturnsInAsync1.js +++ b/tests/baselines/reference/noImplicitReturnsInAsync1.js @@ -8,10 +8,11 @@ async function test(isError: boolean = false) { //// [noImplicitReturnsInAsync1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/noImplicitReturnsInAsync2.js b/tests/baselines/reference/noImplicitReturnsInAsync2.js index e84b42e8a55..64f267459c3 100644 --- a/tests/baselines/reference/noImplicitReturnsInAsync2.js +++ b/tests/baselines/reference/noImplicitReturnsInAsync2.js @@ -37,10 +37,11 @@ async function test7(isError: boolean = true) { //// [noImplicitReturnsInAsync2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/objectRest2.js b/tests/baselines/reference/objectRest2.js index e46d22db80a..e97e1a0498e 100644 --- a/tests/baselines/reference/objectRest2.js +++ b/tests/baselines/reference/objectRest2.js @@ -16,10 +16,11 @@ rootConnection('test'); //// [objectRest2.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/operationsAvailableOnPromisedType.js b/tests/baselines/reference/operationsAvailableOnPromisedType.js index c9f8851fcc8..5772f603037 100644 --- a/tests/baselines/reference/operationsAvailableOnPromisedType.js +++ b/tests/baselines/reference/operationsAvailableOnPromisedType.js @@ -31,10 +31,11 @@ async function fn( //// [operationsAvailableOnPromisedType.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/parenthesizedAsyncArrowFunction.js b/tests/baselines/reference/parenthesizedAsyncArrowFunction.js index 2009a240f0e..916a0e4a045 100644 --- a/tests/baselines/reference/parenthesizedAsyncArrowFunction.js +++ b/tests/baselines/reference/parenthesizedAsyncArrowFunction.js @@ -7,10 +7,11 @@ let foo = (async bar => bar); //// [parenthesizedAsyncArrowFunction.js] // Repro from #20096 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/promiseDefinitionTest.js b/tests/baselines/reference/promiseDefinitionTest.js index a0f503e2f03..c502085e362 100644 --- a/tests/baselines/reference/promiseDefinitionTest.js +++ b/tests/baselines/reference/promiseDefinitionTest.js @@ -6,10 +6,11 @@ const x = foo(); //// [promiseDefinitionTest.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/promiseType.js b/tests/baselines/reference/promiseType.js index d6b82ebb4d5..84d9d713b48 100644 --- a/tests/baselines/reference/promiseType.js +++ b/tests/baselines/reference/promiseType.js @@ -221,10 +221,11 @@ const pc9 = p.then(() => Promise.reject("1"), () => Promise.reject(1)); //// [promiseType.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/promiseTypeStrictNull.js b/tests/baselines/reference/promiseTypeStrictNull.js index 60e0b9b61df..cdee87b5666 100644 --- a/tests/baselines/reference/promiseTypeStrictNull.js +++ b/tests/baselines/reference/promiseTypeStrictNull.js @@ -221,10 +221,11 @@ const pc9 = p.then(() => Promise.reject("1"), () => Promise.reject(1)); //// [promiseTypeStrictNull.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/reachabilityChecks7.js b/tests/baselines/reference/reachabilityChecks7.js index 30addff4aec..8421e1ff594 100644 --- a/tests/baselines/reference/reachabilityChecks7.js +++ b/tests/baselines/reference/reachabilityChecks7.js @@ -31,10 +31,11 @@ let x1 = () => { use("Test"); } //// [reachabilityChecks7.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.js b/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.js index 69e1108ad30..88ae943f92a 100644 --- a/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.js +++ b/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.js @@ -163,10 +163,11 @@ var __extends = (this && this.__extends) || (function () { }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.js b/tests/baselines/reference/thisTypeInFunctionsNegative.js index ed454ee8b70..a3fe0b8ee59 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.js +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.js @@ -181,10 +181,11 @@ const f4 = async (this: {n: number}, m: number) => m + this.n; //// [thisTypeInFunctionsNegative.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; diff --git a/tests/baselines/reference/transformNestedGeneratorsWithTry.js b/tests/baselines/reference/transformNestedGeneratorsWithTry.js index 28f01e07988..84b933cc6a7 100644 --- a/tests/baselines/reference/transformNestedGeneratorsWithTry.js +++ b/tests/baselines/reference/transformNestedGeneratorsWithTry.js @@ -25,10 +25,11 @@ declare module "bluebird" { //// [main.js] "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; From 3206f5fb94d7962c6f0588289a5c670bfc0b4b54 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 23 Jul 2019 06:38:49 -0700 Subject: [PATCH 044/151] When inferring from XXX to T | XXX make no inferece for T (instead of never) --- src/compiler/checker.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0a64e0552e2..72d91c184d7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15515,16 +15515,18 @@ namespace ts { // removing the identically matched constituents. For example, when inferring from // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. if (matchingTypes) { - source = removeTypesFromUnionOrIntersection(source, matchingTypes); - target = removeTypesFromUnionOrIntersection(target, matchingTypes); + const s = removeTypesFromUnionOrIntersection(source, matchingTypes); + const t = removeTypesFromUnionOrIntersection(target, matchingTypes); + if (!(s && t)) return; + source = s; + target = t; } } else if (target.flags & TypeFlags.Union && !(target.flags & TypeFlags.EnumLiteral) || target.flags & TypeFlags.Intersection) { const matched = findMatchedType(source, target); if (matched) { inferFromTypes(matched, matched); - source = target.flags & TypeFlags.Union ? neverType : unknownType; - target = removeTypesFromUnionOrIntersection(target, [matched]); + return; } } else if (target.flags & (TypeFlags.IndexedAccess | TypeFlags.Substitution)) { @@ -15993,7 +15995,7 @@ namespace ts { reducedTypes.push(t); } } - return type.flags & TypeFlags.Union ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return reducedTypes.length ? type.flags & TypeFlags.Union ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes) : undefined; } function hasPrimitiveConstraint(type: TypeParameter): boolean { From 564685692f8103e6b8f90dd47283aa2363ef768f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 23 Jul 2019 06:38:58 -0700 Subject: [PATCH 045/151] Accept new baselines --- .../baselines/reference/unionAndIntersectionInference2.types | 2 +- tests/baselines/reference/unionTypeInference.types | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/baselines/reference/unionAndIntersectionInference2.types b/tests/baselines/reference/unionAndIntersectionInference2.types index 031354506b7..24f24220bd9 100644 --- a/tests/baselines/reference/unionAndIntersectionInference2.types +++ b/tests/baselines/reference/unionAndIntersectionInference2.types @@ -20,7 +20,7 @@ var e1: number | string | boolean; >e1 : string | number | boolean f1(a1); // string ->f1(a1) : never +>f1(a1) : unknown >f1 : (x: string | T) => T >a1 : string diff --git a/tests/baselines/reference/unionTypeInference.types b/tests/baselines/reference/unionTypeInference.types index 6675e63f8c4..304bbcd33ec 100644 --- a/tests/baselines/reference/unionTypeInference.types +++ b/tests/baselines/reference/unionTypeInference.types @@ -104,8 +104,8 @@ const c4 = f3(b); // true >b : boolean const c5 = f3("abc"); // never ->c5 : never ->f3("abc") : never +>c5 : unknown +>f3("abc") : unknown >f3 : (x: string | false | T) => T >"abc" : "abc" From b8e779d89ad939d1740542e8f01347670b116cb0 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 23 Jul 2019 16:28:22 -0700 Subject: [PATCH 046/151] When the exported symbol is merged symbol from declaration use that name to verify quality Fixes #27880 --- src/services/codefixes/importFixes.ts | 7 ++- .../completionsImport_default_symbolName.ts | 44 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/completionsImport_default_symbolName.ts diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 8006d1a0cfd..5f1754c3036 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -445,9 +445,12 @@ namespace ts.codefix { const aliased = checker.getImmediateAliasedSymbol(defaultExport); return aliased && getDefaultExportInfoWorker(aliased, Debug.assertDefined(aliased.parent), checker, compilerOptions); } - else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target!) }; + + if (defaultExport.escapedName !== InternalSymbolName.Default && + defaultExport.escapedName !== InternalSymbolName.ExportEquals) { + return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target!) }; } function getNameForExportDefault(symbol: Symbol): string | undefined { diff --git a/tests/cases/fourslash/completionsImport_default_symbolName.ts b/tests/cases/fourslash/completionsImport_default_symbolName.ts new file mode 100644 index 00000000000..0ede7a1673a --- /dev/null +++ b/tests/cases/fourslash/completionsImport_default_symbolName.ts @@ -0,0 +1,44 @@ +/// + +// @module: commonjs + +// @Filename: /node_modules/@types/range-parser/index.d.ts +////declare function RangeParser(): string; +////declare namespace RangeParser { +//// interface Options { +//// combine?: boolean; +//// } +////} +////export = RangeParser; + +// @Filename: /b.ts +////R/*0*/ + +verify.completions( + { + marker: "0", + includes: { + name: "RangeParser", + kind: "function", + kindModifiers: "declare", + source: "/node_modules/@types/range-parser/index", + sourceDisplay: "range-parser", + hasAction: true, + sortText: completion.SortText.AutoImportSuggestions, + text: `namespace RangeParser +function RangeParser(): string` + }, + preferences: { + includeCompletionsForModuleExports: true + } + }, +); + +verify.applyCodeActionFromCompletion("0", { + name: "RangeParser", + source: "/node_modules/@types/range-parser/index", + description: `Import 'RangeParser' from module "range-parser"`, + newFileContent: `import RangeParser = require("range-parser"); + +R`, +}); From 40fd4efdf6b61dcf1a2265c23d784a4974a5cfc7 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 23 Jul 2019 17:14:50 -0700 Subject: [PATCH 047/151] Strip more kinds of timestamps and versions from dockerfile output (#32519) * Strip more kinds of timestamps and versions from dockerfile output, rewrite office-ui-fabric dockerfile to use new lerna build system * Add another filter for just output * Update user baselines (#23) * Update user baselines (#24) * Strip only maybe-present timestamps * More lenient timestamp filter * Update user baselines (#25) * Simplify and enhance vscode dockerfile to use nightly ts in ts extension, too * Update user baselines (#26) * Update user baselines (#27) --- src/testRunner/externalCompileRunner.ts | 8 +- .../baselines/reference/docker/azure-sdk.log | 65 +- .../reference/docker/office-ui-fabric.log | 795 ++++++++++-------- tests/baselines/reference/docker/vscode.log | 31 +- .../cases/docker/office-ui-fabric/Dockerfile | 29 +- tests/cases/docker/vscode/Dockerfile | 10 +- tests/cases/user/prettier/prettier | 2 +- 7 files changed, 495 insertions(+), 445 deletions(-) diff --git a/src/testRunner/externalCompileRunner.ts b/src/testRunner/externalCompileRunner.ts index dbe7bc5854f..a47c0b59e24 100644 --- a/src/testRunner/externalCompileRunner.ts +++ b/src/testRunner/externalCompileRunner.ts @@ -185,7 +185,8 @@ function stripRushStageNumbers(result: string): string { * so we purge as much of the gulp output as we can */ function sanitizeUnimportantGulpOutput(result: string): string { - return result.replace(/^.*(\] (Starting)|(Finished)).*$/gm, "") // task start/end messages (nondeterministic order) + return result.replace(/^.*(\] (Starting)|(Finished)).*$/gm, "") // "gulp" task start/end messages (nondeterministic order) + .replace(/^.*(\] . (finished)|(started)).*$/gm, "") // "just" task start/end messages (nondeterministic order) .replace(/^.*\] Respawned to PID: \d+.*$/gm, "") // PID of child is OS and system-load dependent (likely stableish in a container but still dangerous) .replace(/\n+/g, "\n"); } @@ -193,14 +194,17 @@ function sanitizeUnimportantGulpOutput(result: string): string { function sanitizeTimestamps(result: string): string { return result.replace(/\[\d?\d:\d\d:\d\d (A|P)M\]/g, "[XX:XX:XX XM]") .replace(/\[\d?\d:\d\d:\d\d\]/g, "[XX:XX:XX]") + .replace(/\/\d+-\d+-[\d_TZ]+-debug.log/g, "\/XXXX-XX-XXXXXXXXX-debug.log") .replace(/\d+(\.\d+)? sec(onds?)?/g, "? seconds") .replace(/\d+(\.\d+)? min(utes?)?/g, "") - .replace(/\d+(\.\d+)?( m)?s/g, "?s"); + .replace(/\d+(\.\d+)? ?m?s/g, "?s") + .replace(/ \(\?s\)/g, ""); } function sanitizeVersionSpecifiers(result: string): string { return result .replace(/\d+.\d+.\d+-insiders.\d\d\d\d\d\d\d\d/g, "X.X.X-insiders.xxxxxxxx") + .replace(/Rush Multi-Project Build Tool (\d+)\.\d+\.\d+/g, "Rush Multi-Project Build Tool $1.X.X") .replace(/([@v\()])\d+\.\d+\.\d+/g, "$1X.X.X"); } diff --git a/tests/baselines/reference/docker/azure-sdk.log b/tests/baselines/reference/docker/azure-sdk.log index a75af93aee1..8728a9a8110 100644 --- a/tests/baselines/reference/docker/azure-sdk.log +++ b/tests/baselines/reference/docker/azure-sdk.log @@ -1,54 +1,41 @@ Exit Code: 1 Standard output: -Rush Multi-Project Build Tool 5.10.1 - https://rushjs.io +Rush Multi-Project Build Tool 5.X.X - https://rushjs.io Starting "rush rebuild" -Executing a maximum of 1 simultaneous processes... -[@azure/cosmos] started -XX of XX: [@azure/cosmos] completed successfully in ? seconds -[@azure/event-processor-host] started -XX of XX: [@azure/event-processor-host] completed successfully in ? seconds -[@azure/service-bus] started -Warning: You have changed the public API signature for this project. Updating review/service-bus.api.md -[@azure/storage-blob] started -XX of XX: [@azure/storage-blob] completed successfully in ? seconds -[@azure/storage-file] started -XX of XX: [@azure/storage-file] completed successfully in ? seconds -[@azure/storage-queue] started -XX of XX: [@azure/storage-queue] completed successfully in ? seconds -[@azure/template] started -XX of XX: [@azure/template] completed successfully in ? seconds -[testhub] started -XX of XX: [testhub] completed successfully in ? seconds -[@azure/abort-controller] started +Executing a maximum of ?simultaneous processes... XX of XX: [@azure/abort-controller] completed successfully in ? seconds -[@azure/core-asynciterator-polyfill] started XX of XX: [@azure/core-asynciterator-polyfill] completed successfully in ? seconds -[@azure/core-auth] started +XX of XX: [@azure/core-paging] completed successfully in ? seconds +XX of XX: [@azure/cosmos] completed successfully in ? seconds +XX of XX: [@azure/event-processor-host] completed successfully in ? seconds +Warning: You have changed the public API signature for this project. Updating review/service-bus.api.md +XX of XX: [@azure/storage-blob] completed successfully in ? seconds +XX of XX: [@azure/storage-file] completed successfully in ? seconds +XX of XX: [@azure/storage-queue] completed successfully in ? seconds +XX of XX: [@azure/template] completed successfully in ? seconds +XX of XX: [testhub] completed successfully in ? seconds XX of XX: [@azure/core-auth] completed successfully in ? seconds -[@azure/core-http] started npm ERR! code ELIFECYCLE npm ERR! errno 2 -npm ERR! @azure/core-http@X.X.X-preview.1 build:tsc: `tsc -p tsconfig.es.json` +npm ERR! @azure/core-http@X.X.X-preview.2 build:tsc: `tsc -p tsconfig.es.json` npm ERR! Exit status 2 npm ERR! -npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:tsc script. +npm ERR! Failed at the @azure/core-http@X.X.X-preview.2 build:tsc script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_496Z-debug.log +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log ERROR: "build:tsc" exited with 2. npm ERR! code ELIFECYCLE npm ERR! errno 1 -npm ERR! @azure/core-http@X.X.X-preview.1 build:lib: `run-s build:tsc build:rollup build:minify-browser` +npm ERR! @azure/core-http@X.X.X-preview.2 build:lib: `run-s build:tsc build:rollup build:minify-browser` npm ERR! Exit status 1 npm ERR! -npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:lib script. +npm ERR! Failed at the @azure/core-http@X.X.X-preview.2 build:lib script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_533Z-debug.log +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log ERROR: "build:lib" exited with 1. -[@azure/core-paging] started -XX of XX: [@azure/core-paging] completed successfully in ? seconds SUCCESS (11) ================================ @azure/abort-controller (? seconds) @@ -83,23 +70,23 @@ FAILURE (1) @azure/core-http (? seconds) npm ERR! code ELIFECYCLE npm ERR! errno 2 -npm ERR! @azure/core-http@X.X.X-preview.1 build:tsc: `tsc -p tsconfig.es.json` +npm ERR! @azure/core-http@X.X.X-preview.2 build:tsc: `tsc -p tsconfig.es.json` npm ERR! Exit status 2 npm ERR! -npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:tsc script. +npm ERR! Failed at the @azure/core-http@X.X.X-preview.2 build:tsc script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_496Z-debug.log +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log ERROR: "build:tsc" exited with 2. npm ERR! code ELIFECYCLE npm ERR! errno 1 -npm ERR! @azure/core-http@X.X.X-preview.1 build:lib: `run-s build:tsc build:rollup build:minify-browser` +npm ERR! @azure/core-http@X.X.X-preview.2 build:lib: `run-s build:tsc build:rollup build:minify-browser` npm ERR! Exit status 1 npm ERR! -npm ERR! Failed at the @azure/core-http@X.X.X-preview.1 build:lib script. +npm ERR! Failed at the @azure/core-http@X.X.X-preview.2 build:lib script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: -npm ERR! /root/.npm/_logs/2019-07-19T13_40_31_533Z-debug.log +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log ERROR: "build:lib" exited with 1. ================================ Error: Project(s) failed to build @@ -112,10 +99,10 @@ Your version of Node.js (X.X.X) has not been tested with this release of Rush. T XX of XX: [@azure/service-bus] completed with warnings in ? seconds XX of XX: [@azure/core-http] failed to build! XX of XX: [@azure/core-arm] blocked by [@azure/core-http]! -XX of XX: [@azure/identity] blocked by [@azure/core-http]! -XX of XX: [@azure/core-amqp] blocked by [@azure/core-http]! -XX of XX: [@azure/event-hubs] blocked by [@azure/core-http]! XX of XX: [@azure/keyvault-certificates] blocked by [@azure/core-http]! XX of XX: [@azure/keyvault-keys] blocked by [@azure/core-http]! XX of XX: [@azure/keyvault-secrets] blocked by [@azure/core-http]! +XX of XX: [@azure/identity] blocked by [@azure/core-http]! +XX of XX: [@azure/core-amqp] blocked by [@azure/core-http]! +XX of XX: [@azure/event-hubs] blocked by [@azure/core-http]! [@azure/core-http] Returned error code: 1 diff --git a/tests/baselines/reference/docker/office-ui-fabric.log b/tests/baselines/reference/docker/office-ui-fabric.log index 888e20cac4b..745bdff4193 100644 --- a/tests/baselines/reference/docker/office-ui-fabric.log +++ b/tests/baselines/reference/docker/office-ui-fabric.log @@ -1,371 +1,436 @@ Exit Code: 1 Standard output: - -Rush Multi-Project Build Tool 5.6.0 - https://rushjs.io -Starting "rush rebuild" -Executing a maximum of 1 simultaneous processes... -[@uifabric/prettier-rules] started -XX of XX: [@uifabric/prettier-rules] completed successfully in ? seconds -[@uifabric/tslint-rules] started -XX of XX: [@uifabric/tslint-rules] completed successfully in ? seconds -[@uifabric/codepen-loader] started -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. - PASS src/__tests__/codepenTransform.test.ts - codepen transform - ✓ handles examples with function components (256ms) - ✓ handles examples with class components (38ms) - ✓ handles examples importing exampleData (125ms) - ✓ handles examples importing TestImages (33ms) - ✓ handles examples importing PeopleExampleData (270ms) -Test Suites: 1 passed, 1 total -Tests: 5 passed, 5 total -Snapshots: 4 passed, 4 total -Time: ?s -Ran all test suites. -[@uifabric/build] started -XX of XX: [@uifabric/build] completed successfully in ? seconds -[@uifabric/migration] started -XX of XX: [@uifabric/migration] completed successfully in ? seconds -[@uifabric/set-version] started -XX of XX: [@uifabric/set-version] completed successfully in ? seconds -[@uifabric/merge-styles] started -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -[@uifabric/jest-serializer-merge-styles] started -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -[@uifabric/test-utilities] started -XX of XX: [@uifabric/test-utilities] completed successfully in ? seconds -[@uifabric/utilities] started -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -[@uifabric/styling] started -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -[@uifabric/file-type-icons] started -XX of XX: [@uifabric/file-type-icons] completed successfully in ? seconds -[@uifabric/foundation] started -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. - ● createFactory › passes componentProps without userProps - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:205:73) - ● createFactory › passes userProp string as child - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:210:76) - ● createFactory › passes userProp integer as child - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:220:76) - ● createFactory › passes userProp string as defaultProp - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:225:92) - ● createFactory › passes userProp integer as defaultProp - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:235:92) - ● createFactory › merges userProps over componentProps - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:245:84) - ● createFactory › renders div and userProp integer as children - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:255:86) - ● createFactory › renders div and userProp string as children - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:266:86) - ● createFactory › renders userProp span function without component props - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:288:61) - ● createFactory › renders userProp span function with component props - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:301:61) - ● createFactory › renders userProp span component with component props - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:314:61) - ● createFactory › passes props and type arguments to userProp function - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at Object. (src/slots.test.tsx:334:43) - ● getSlots › creates slots and passes merged props to them - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at _renderSlot (src/slots.tsx:221:100) - at Object.slot [as testSlot1] (src/slots.tsx:142:16) - at Object. (src/slots.test.tsx:399:24) -[XX:XX:XX XM] x Error detected while running 'jest' -[XX:XX:XX XM] x ------------------------------------ -[XX:XX:XX XM] x Error: Command failed: /usr/local/bin/node /office-ui-fabric-react/common/temp/node_modules/jest/bin/jest.js --config /office-ui-fabric-react/packages/foundation/jest.config.js --passWithNoTests --colors - at ChildProcess. (/office-ui-fabric-react/common/temp/node_modules/.registry.npmjs.org/just-scripts-utils/0.8.2/node_modules/just-scripts-utils/lib/exec.js:70:31) - at ChildProcess.emit (events.js:203:13) - at ChildProcess.EventEmitter.emit (domain.js:494:23) - at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12) -[XX:XX:XX XM] x ------------------------------------ -[XX:XX:XX XM] x finished 'validate' in ?s with errors -[XX:XX:XX XM] x finished 'build' in ?s with errors -[XX:XX:XX XM] x Error previously detected. See above for error messages. -[@uifabric/icons] started -XX of XX: [@uifabric/icons] completed successfully in ? seconds -[@uifabric/webpack-utils] started -XX of XX: [@uifabric/webpack-utils] completed successfully in ? seconds -SUCCESS (9) -================================ -@uifabric/build (? seconds) -@uifabric/file-type-icons (? seconds) -@uifabric/icons (? seconds) -@uifabric/migration (? seconds) -@uifabric/prettier-rules (? seconds) -@uifabric/set-version (? seconds) -@uifabric/test-utilities (? seconds) -@uifabric/tslint-rules (? seconds) -@uifabric/webpack-utils (? seconds) -================================ -SUCCESS WITH WARNINGS (5) -================================ -@uifabric/codepen-loader (? seconds) -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. - PASS src/__tests__/codepenTransform.test.ts - codepen transform - ✓ handles examples with function components (256ms) - ✓ handles examples with class components (38ms) - ✓ handles examples importing exampleData (125ms) - ✓ handles examples importing TestImages (33ms) - ✓ handles examples importing PeopleExampleData (270ms) -Test Suites: 1 passed, 1 total -Tests: 5 passed, 5 total -Snapshots: 4 passed, 4 total -Time: ?s -Ran all test suites. -@uifabric/jest-serializer-merge-styles (? seconds) -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -@uifabric/merge-styles (? seconds) -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -@uifabric/styling (? seconds) -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -@uifabric/utilities (? seconds) -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. -================================ -BLOCKED (27) -================================ -@uifabric/api-docs -@uifabric/azure-themes -@uifabric/charting -@uifabric/date-time -@uifabric/example-app-base -@uifabric/experiments -@uifabric/fabric-website -@uifabric/fabric-website-resources -@uifabric/fluent-theme -@uifabric/foundation-scenarios -@uifabric/lists -@uifabric/mdl2-theme -@uifabric/pr-deploy-site -@uifabric/react-cards -@uifabric/theme-samples -@uifabric/tsx-editor -@uifabric/variants -a11y-tests -dom-tests -office-ui-fabric-react -perf-test -server-rendered-app -ssr-tests -test-bundles -theming-designer -todo-app -vr-tests -================================ -FAILURE (1) -================================ -@uifabric/foundation (? seconds) -ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. - ● createFactory › passes componentProps without userProps - RangeError: Invalid array length - 189 | for (const props of allProps) { - 190 | classNames.push(props && props.className); - > 191 | assign(finalProps, ...(props as any)); - | ^ - 192 | } - 193 | -[...179 lines omitted...] - 193 | - 194 | finalProps.className = mergeStyles(defaultStyles, classNames); - at Object.__spreadArrays (../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.js:182:22) - at _constructFinalProps (src/slots.tsx:191:11) - at result (src/slots.tsx:88:24) - at _renderSlot (src/slots.tsx:221:100) - at Object.slot [as testSlot1] (src/slots.tsx:142:16) - at Object. (src/slots.test.tsx:399:24) -[XX:XX:XX XM] x Error detected while running 'jest' -[XX:XX:XX XM] x ------------------------------------ -[XX:XX:XX XM] x Error: Command failed: /usr/local/bin/node /office-ui-fabric-react/common/temp/node_modules/jest/bin/jest.js --config /office-ui-fabric-react/packages/foundation/jest.config.js --passWithNoTests --colors - at ChildProcess. (/office-ui-fabric-react/common/temp/node_modules/.registry.npmjs.org/just-scripts-utils/0.8.2/node_modules/just-scripts-utils/lib/exec.js:70:31) - at ChildProcess.emit (events.js:203:13) - at ChildProcess.EventEmitter.emit (domain.js:494:23) - at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12) -[XX:XX:XX XM] x ------------------------------------ -[XX:XX:XX XM] x finished 'validate' in ?s with errors -[XX:XX:XX XM] x finished 'build' in ?s with errors -[XX:XX:XX XM] x Error previously detected. See above for error messages. -================================ -Error: Project(s) failed to build -rush rebuild - Errors! ( ? seconds) +@uifabric/codepen-loader: yarn run vX.X.X +@uifabric/codepen-loader: $ just-scripts build --production --lint +@uifabric/codepen-loader: [XX:XX:XX XM] ■ Removing [lib, temp, dist, coverage, lib-commonjs] +@uifabric/codepen-loader: [XX:XX:XX XM] ■ Copying [../office-ui-fabric-react/src/utilities/exampleData.ts, ../office-ui-fabric-react/src/components/ExtendedPicker/examples/PeopleExampleData.ts, ../office-ui-fabric-react/src/common/TestImages.ts] to 'lib' +@uifabric/codepen-loader: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/codepen-loader/tsconfig.json +@uifabric/codepen-loader: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --module commonjs --outDir "./lib" --project "/office-ui-fabric-react/packages/codepen-loader/tsconfig.json" +@uifabric/codepen-loader: [XX:XX:XX XM] ■ Running Jest +@uifabric/codepen-loader: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/codepen-loader/jest.config.js" --passWithNoTests --colors +@uifabric/codepen-loader: PASS src/__tests__/codepenTransform.test.ts +@uifabric/codepen-loader: Done in ?s. +@uifabric/build: yarn run vX.X.X +@uifabric/build: $ node ./just-scripts.js no-op --production --lint +@uifabric/build: Done in ?s. +@uifabric/migration: yarn run vX.X.X +@uifabric/migration: $ just-scripts build --production --lint +@uifabric/migration: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/migration: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/migration/tsconfig.json +@uifabric/migration: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module commonjs --project "/office-ui-fabric-react/packages/migration/tsconfig.json" +@uifabric/migration: Done in ?s. +@uifabric/set-version: yarn run vX.X.X +@uifabric/set-version: $ just-scripts build --production --lint +@uifabric/set-version: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/set-version: [XX:XX:XX XM] ■ Running tslint +@uifabric/set-version: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/set-version: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/set-version/tsconfig.json +@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" +@uifabric/set-version: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/set-version/tsconfig.json +@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" +@uifabric/set-version: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/set-version/tsconfig.json +@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" +@uifabric/set-version: [XX:XX:XX XM] ■ Running Webpack +@uifabric/set-version: [XX:XX:XX XM] ■ Webpack Config Path: null +@uifabric/set-version: [XX:XX:XX XM] ■ webpack.config.js not found, skipping webpack +@uifabric/set-version: Done in ?s. +@uifabric/webpack-utils: yarn run vX.X.X +@uifabric/webpack-utils: $ just-scripts build --production --lint +@uifabric/webpack-utils: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/webpack-utils: [XX:XX:XX XM] ■ Running tslint +@uifabric/webpack-utils: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/webpack-utils/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/webpack-utils: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/webpack-utils/tsconfig.json +@uifabric/webpack-utils: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module commonjs --project "/office-ui-fabric-react/packages/webpack-utils/tsconfig.json" +@uifabric/webpack-utils: Done in ?s. +@uifabric/merge-styles: yarn run vX.X.X +@uifabric/merge-styles: $ just-scripts build --production --lint +@uifabric/merge-styles: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/merge-styles: [XX:XX:XX XM] ■ Running tslint +@uifabric/merge-styles: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/merge-styles/tsconfig.json +@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" +@uifabric/merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/merge-styles/tsconfig.json +@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" +@uifabric/merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/merge-styles/tsconfig.json +@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" +@uifabric/merge-styles: [XX:XX:XX XM] ■ Running Jest +@uifabric/merge-styles: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/merge-styles/jest.config.js" --passWithNoTests --colors +@uifabric/merge-styles: [XX:XX:XX XM] ■ Running Webpack +@uifabric/merge-styles: [XX:XX:XX XM] ■ Webpack Config Path: /office-ui-fabric-react/packages/merge-styles/webpack.config.js +@uifabric/merge-styles: Webpack version: 4.29.5 +@uifabric/merge-styles: PASS src/styleToClassName.test.ts +@uifabric/merge-styles: PASS src/mergeStyleSets.test.ts +@uifabric/merge-styles: PASS src/concatStyleSets.test.ts +@uifabric/merge-styles: PASS src/mergeStyles.test.ts +@uifabric/merge-styles: PASS src/transforms/rtlifyRules.test.ts +@uifabric/merge-styles: PASS src/transforms/prefixRules.test.ts +@uifabric/merge-styles: PASS src/transforms/provideUnits.test.ts +@uifabric/merge-styles: PASS src/keyframes.test.ts +@uifabric/merge-styles: PASS src/Stylesheet.test.ts +@uifabric/merge-styles: PASS src/extractStyleParts.test.ts +@uifabric/merge-styles: PASS src/server.test.ts +@uifabric/merge-styles: PASS src/fontFace.test.ts +@uifabric/merge-styles: PASS src/transforms/kebabRules.test.ts +@uifabric/merge-styles: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/merge-styles/lib/index.d.ts' +@uifabric/merge-styles: Done in ?s. +@uifabric/jest-serializer-merge-styles: yarn run vX.X.X +@uifabric/jest-serializer-merge-styles: $ just-scripts build --production --lint +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running Jest +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/jest-serializer-merge-styles/jest.config.js" --passWithNoTests --colors +@uifabric/jest-serializer-merge-styles: PASS src/index.test.tsx +@uifabric/jest-serializer-merge-styles: Done in ?s. +@uifabric/test-utilities: yarn run vX.X.X +@uifabric/test-utilities: $ just-scripts build --production --lint +@uifabric/test-utilities: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/test-utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/test-utilities/tsconfig.json +@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" +@uifabric/test-utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/test-utilities/tsconfig.json +@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" +@uifabric/test-utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/test-utilities/tsconfig.json +@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" +@uifabric/test-utilities: Done in ?s. +@uifabric/utilities: yarn run vX.X.X +@uifabric/utilities: $ just-scripts build --production --lint +@uifabric/utilities: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/utilities: [XX:XX:XX XM] ■ Running tslint +@uifabric/utilities: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/utilities/tsconfig.json +@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" +@uifabric/utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/utilities/tsconfig.json +@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" +@uifabric/utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/utilities/tsconfig.json +@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" +@uifabric/utilities: [XX:XX:XX XM] ■ Running Jest +@uifabric/utilities: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/utilities/jest.config.js" --passWithNoTests --colors +@uifabric/utilities: [XX:XX:XX XM] ■ Running Webpack +@uifabric/utilities: [XX:XX:XX XM] ■ Webpack Config Path: null +@uifabric/utilities: [XX:XX:XX XM] ■ webpack.config.js not found, skipping webpack +@uifabric/utilities: PASS src/warn/warnControlledUsage.test.ts +@uifabric/utilities: PASS src/focus.test.tsx +@uifabric/utilities: PASS src/styled.test.tsx +@uifabric/utilities: PASS src/EventGroup.test.ts +@uifabric/utilities: PASS src/array.test.ts +@uifabric/utilities: PASS src/customizations/Customizer.test.tsx +@uifabric/utilities: PASS src/math.test.ts +@uifabric/utilities: PASS src/warn/warn.test.ts +@uifabric/utilities: PASS src/dom/dom.test.ts +@uifabric/utilities: PASS src/customizations/customizable.test.tsx +@uifabric/utilities: PASS src/initials.test.ts +@uifabric/utilities: PASS src/selection/Selection.test.ts +@uifabric/utilities: PASS src/initializeFocusRects.test.ts +@uifabric/utilities: PASS src/memoize.test.ts +@uifabric/utilities: PASS src/osDetector.test.ts +@uifabric/utilities: PASS src/mobileDetector.test.ts +@uifabric/utilities: PASS src/aria.test.ts +@uifabric/utilities: PASS src/rtl.test.ts +@uifabric/utilities: PASS src/setFocusVisibility.test.ts +@uifabric/utilities: PASS src/properties.test.ts +@uifabric/utilities: PASS src/asAsync.test.tsx +@uifabric/utilities: PASS src/object.test.ts +@uifabric/utilities: PASS src/classNamesFunction.test.ts +@uifabric/utilities: PASS src/merge.test.ts +@uifabric/utilities: PASS src/customizations/Customizations.test.ts +@uifabric/utilities: PASS src/safeSetTimeout.test.tsx +@uifabric/utilities: PASS src/safeRequestAnimationFrame.test.tsx +@uifabric/utilities: PASS src/overflow.test.ts +@uifabric/utilities: PASS src/appendFunction.test.ts +@uifabric/utilities: PASS src/controlled.test.ts +@uifabric/utilities: PASS src/extendComponent.test.tsx +@uifabric/utilities: PASS src/initializeComponentRef.test.tsx +@uifabric/utilities: PASS src/BaseComponent.test.tsx +@uifabric/utilities: PASS src/keyboard.test.ts +@uifabric/utilities: PASS src/css.test.ts +@uifabric/utilities: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/utilities/lib/index.d.ts' +@uifabric/utilities: Done in ?s. +@uifabric/styling: yarn run vX.X.X +@uifabric/styling: $ just-scripts build --production --lint +@uifabric/styling: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/styling: [XX:XX:XX XM] ■ Running tslint +@uifabric/styling: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/styling/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/styling: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/styling/tsconfig.json +@uifabric/styling: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/styling/tsconfig.json" +@uifabric/styling: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/styling/tsconfig.json +@uifabric/styling: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/styling/tsconfig.json" +@uifabric/styling: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/styling/tsconfig.json +@uifabric/styling: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/styling/tsconfig.json" +@uifabric/styling: [XX:XX:XX XM] ■ Running Jest +@uifabric/styling: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/styling/jest.config.js" --passWithNoTests --colors +@uifabric/styling: [XX:XX:XX XM] ■ Running Webpack +@uifabric/styling: [XX:XX:XX XM] ■ Webpack Config Path: null +@uifabric/styling: [XX:XX:XX XM] ■ webpack.config.js not found, skipping webpack +@uifabric/styling: PASS src/styles/theme.test.ts +@uifabric/styling: PASS src/styles/scheme.test.ts +@uifabric/styling: PASS src/styles/getGlobalClassNames.test.ts +@uifabric/styling: PASS src/utilities/icons.test.ts +@uifabric/styling: PASS src/styles/fonts.test.ts +@uifabric/styling: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/styling/lib/index.d.ts' +@uifabric/styling: Done in ?s. +@uifabric/file-type-icons: yarn run vX.X.X +@uifabric/file-type-icons: $ just-scripts build --production --lint +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Running tslint +@uifabric/file-type-icons: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/file-type-icons/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/file-type-icons/tsconfig.json +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/file-type-icons/tsconfig.json" +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/file-type-icons/tsconfig.json +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/file-type-icons/tsconfig.json" +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/file-type-icons/tsconfig.json +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/file-type-icons/tsconfig.json" +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Running Webpack +@uifabric/file-type-icons: [XX:XX:XX XM] ■ Webpack Config Path: null +@uifabric/file-type-icons: [XX:XX:XX XM] ■ webpack.config.js not found, skipping webpack +@uifabric/file-type-icons: Done in ?s. +@uifabric/foundation: yarn run vX.X.X +@uifabric/foundation: $ just-scripts build --production --lint +@uifabric/foundation: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] +@uifabric/foundation: [XX:XX:XX XM] ■ Running tslint +@uifabric/foundation: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/foundation/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib +@uifabric/foundation: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/foundation/tsconfig.json +@uifabric/foundation: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/foundation/tsconfig.json" +@uifabric/foundation: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/foundation/tsconfig.json +@uifabric/foundation: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module es2015 --project "/office-ui-fabric-react/packages/foundation/tsconfig.json" +@uifabric/foundation: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/foundation/tsconfig.json +@uifabric/foundation: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/foundation/tsconfig.json" +@uifabric/foundation: [XX:XX:XX XM] ■ Running Jest +@uifabric/foundation: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/foundation/jest.config.js" --passWithNoTests --colors +@uifabric/foundation: [XX:XX:XX XM] ■ Running Webpack +@uifabric/foundation: [XX:XX:XX XM] ■ Webpack Config Path: /office-ui-fabric-react/packages/foundation/webpack.config.js +@uifabric/foundation: Webpack version: 4.29.5 +@uifabric/foundation: FAIL src/slots.test.tsx +@uifabric/foundation: PASS src/hooks/controlled.test.tsx +@uifabric/foundation: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. Standard error: -Your version of Node.js (X.X.X) has not been tested with this release of Rush. The Rush team will not accept issue reports for it. Please consider upgrading Rush or downgrading Node.js. -XX of XX: [@uifabric/codepen-loader] completed with warnings in ? seconds -XX of XX: [@uifabric/merge-styles] completed with warnings in ? seconds -XX of XX: [@uifabric/jest-serializer-merge-styles] completed with warnings in ? seconds -XX of XX: [@uifabric/utilities] completed with warnings in ? seconds -XX of XX: [@uifabric/styling] completed with warnings in ? seconds -XX of XX: [@uifabric/foundation] failed to build! -XX of XX: [@uifabric/experiments] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/fabric-website] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/pr-deploy-site] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/react-cards] blocked by [@uifabric/foundation]! -XX of XX: [theming-designer] blocked by [@uifabric/foundation]! -XX of XX: [vr-tests] blocked by [@uifabric/foundation]! -XX of XX: [dom-tests] blocked by [@uifabric/foundation]! -XX of XX: [perf-test] blocked by [@uifabric/foundation]! -XX of XX: [test-bundles] blocked by [@uifabric/foundation]! -XX of XX: [office-ui-fabric-react] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/api-docs] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/fabric-website-resources] blocked by [@uifabric/foundation]! -XX of XX: [a11y-tests] blocked by [@uifabric/foundation]! -XX of XX: [ssr-tests] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/azure-themes] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/charting] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/date-time] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/example-app-base] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/foundation-scenarios] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/lists] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/fluent-theme] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/tsx-editor] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/mdl2-theme] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/theme-samples] blocked by [@uifabric/foundation]! -XX of XX: [@uifabric/variants] blocked by [@uifabric/foundation]! -XX of XX: [server-rendered-app] blocked by [@uifabric/foundation]! -XX of XX: [todo-app] blocked by [@uifabric/foundation]! -[@uifabric/foundation] Returned error code: 1 +info cli using local version of lerna +lerna notice cli vX.X.X +lerna info Executing command in 40 packages: "yarn run build --production --lint" +@uifabric/codepen-loader: ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. +@uifabric/set-version: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect +@uifabric/merge-styles: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect +@uifabric/merge-styles: ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. +@uifabric/jest-serializer-merge-styles: ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. +@uifabric/utilities: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect +@uifabric/utilities: ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. +@uifabric/styling: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect +@uifabric/styling: ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. +@uifabric/file-type-icons: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect +@uifabric/foundation: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect +@uifabric/foundation: ts-jest[versions] (WARN) Version X.X.X-insiders.xxxxxxxx of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=2.7.0 <4.0.0). Please do not report issues in ts-jest if you are using unsupported versions. +@uifabric/foundation: ● createFactory › passes componentProps without userProps +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:205:73) +@uifabric/foundation: ● createFactory › passes userProp string as child +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:210:76) +@uifabric/foundation: ● createFactory › passes userProp integer as child +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:220:76) +@uifabric/foundation: ● createFactory › passes userProp string as defaultProp +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:225:92) +@uifabric/foundation: ● createFactory › passes userProp integer as defaultProp +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:235:92) +@uifabric/foundation: ● createFactory › merges userProps over componentProps +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:245:84) +@uifabric/foundation: ● createFactory › renders div and userProp integer as children +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:255:86) +@uifabric/foundation: ● createFactory › renders div and userProp string as children +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:266:86) +@uifabric/foundation: ● createFactory › renders userProp span function without component props +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:288:61) +@uifabric/foundation: ● createFactory › renders userProp span function with component props +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:301:61) +@uifabric/foundation: ● createFactory › renders userProp span component with component props +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:314:61) +@uifabric/foundation: ● createFactory › passes props and type arguments to userProp function +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at Object. (src/slots.test.tsx:334:43) +@uifabric/foundation: ● getSlots › creates slots and passes merged props to them +@uifabric/foundation: RangeError: Invalid array length +@uifabric/foundation: +@uifabric/foundation: 189 | for (const props of allProps) { +@uifabric/foundation: 190 | classNames.push(props && props.className); +@uifabric/foundation: > 191 | assign(finalProps, ...(props as any)); +@uifabric/foundation: | ^ +@uifabric/foundation: 192 | } +@uifabric/foundation: 193 | +@uifabric/foundation: 194 | finalProps.className = mergeStyles(defaultStyles, classNames); +@uifabric/foundation: +@uifabric/foundation: at Object.__spreadArrays (../../node_modules/tslib/tslib.js:182:22) +@uifabric/foundation: at _constructFinalProps (src/slots.tsx:191:11) +@uifabric/foundation: at result (src/slots.tsx:88:24) +@uifabric/foundation: at _renderSlot (src/slots.tsx:221:100) +@uifabric/foundation: at Object.slot [as testSlot1] (src/slots.tsx:142:16) +@uifabric/foundation: at Object. (src/slots.test.tsx:399:24) +@uifabric/foundation: [XX:XX:XX XM] x Error detected while running 'jest' +@uifabric/foundation: [XX:XX:XX XM] x ------------------------------------ +@uifabric/foundation: [XX:XX:XX XM] x Error: Command failed: /usr/local/bin/node /office-ui-fabric-react/node_modules/jest/bin/jest.js --config /office-ui-fabric-react/packages/foundation/jest.config.js --passWithNoTests --colors +@uifabric/foundation: at ChildProcess. (/office-ui-fabric-react/node_modules/just-scripts-utils/lib/exec.js:70:31) +@uifabric/foundation: at ChildProcess.emit (events.js:203:13) +@uifabric/foundation: at ChildProcess.EventEmitter.emit (domain.js:494:23) +@uifabric/foundation: at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12) +@uifabric/foundation: [XX:XX:XX XM] x ------------------------------------ +@uifabric/foundation: [XX:XX:XX XM] x Error previously detected. See above for error messages. +@uifabric/foundation: [XX:XX:XX XM] x Other tasks that did not complete: [webpack] +@uifabric/foundation: error Command failed with exit code 1. +lerna ERR! yarn run build --production --lint exited 1 in '@uifabric/foundation' +lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately. diff --git a/tests/baselines/reference/docker/vscode.log b/tests/baselines/reference/docker/vscode.log index 8f23cb6719d..4775203f50e 100644 --- a/tests/baselines/reference/docker/vscode.log +++ b/tests/baselines/reference/docker/vscode.log @@ -4,31 +4,24 @@ yarn run vX.X.X $ gulp compile --max_old_space_size=4095 [XX:XX:XX] Node flags detected: --max_old_space_size=4095 [XX:XX:XX] Using gulpfile /vscode/gulpfile.js -[XX:XX:XX] Error: /vscode/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts(560,5): Type 'null' is not assignable to type 'string'. -[XX:XX:XX] Error: /vscode/src/vs/base/browser/ui/menu/menubar.ts(742,7): Type '"underline" | null' is not assignable to type 'string'. - Type 'null' is not assignable to type 'string'. -[XX:XX:XX] Error: /vscode/src/vs/editor/browser/controller/textAreaInput.ts(208,33): Property 'locale' does not exist on type 'CompositionEvent'. -[XX:XX:XX] Error: /vscode/src/vs/editor/browser/controller/textAreaInput.ts(225,33): Property 'locale' does not exist on type 'CompositionEvent'. -[XX:XX:XX] Error: /vscode/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts(560,5): Type 'null' is not assignable to type 'string'. -[XX:XX:XX] Error: /vscode/src/vs/base/browser/ui/menu/menubar.ts(742,7): Type '"underline" | null' is not assignable to type 'string'. - Type 'null' is not assignable to type 'string'. -[XX:XX:XX] Error: /vscode/src/vs/editor/browser/controller/textAreaInput.ts(208,33): Property 'locale' does not exist on type 'CompositionEvent'. -[XX:XX:XX] Error: /vscode/src/vs/editor/browser/controller/textAreaInput.ts(225,33): Property 'locale' does not exist on type 'CompositionEvent'. +[XX:XX:XX] Error: /vscode/node_modules/@types/node/index.d.ts(179,11): Duplicate identifier 'IteratorResult'. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. Standard error: -[XX:XX:XX] 'compile' errored after -[XX:XX:XX] Error: Found 4 errors +{"type":"warning","data":"package.json: No license field"} +{"type":"warning","data":"../package.json: No license field"} +{"type":"warning","data":"vscode-web@X.X.X: No license field"} +[XX:XX:XX] 'compile' errored after ?s +[XX:XX:XX] Error: Found 1 errors at Stream. (/vscode/build/lib/reporter.js:74:29) at _end (/vscode/node_modules/through/index.js:65:9) at Stream.stream.end (/vscode/node_modules/through/index.js:74:5) - at Stream.onend (internal/streams/legacy.js:42:10) - at Stream.emit (events.js:203:15) - at Stream.EventEmitter.emit (domain.js:466:23) - at drain (/vscode/node_modules/through/index.js:34:23) - at Stream.stream.queue.stream.push (/vscode/node_modules/through/index.js:45:5) - at Stream.end (/vscode/node_modules/through/index.js:15:35) - at _end (/vscode/node_modules/through/index.js:65:9) + at StreamFilter.onend (/vscode/node_modules/readable-stream/lib/_stream_readable.js:570:10) + at Object.onceWrapper (events.js:286:20) + at StreamFilter.emit (events.js:203:15) + at StreamFilter.EventEmitter.emit (domain.js:466:23) + at endReadableNT (/vscode/node_modules/readable-stream/lib/_stream_readable.js:992:12) + at process._tickCallback (internal/process/next_tick.js:63:19) error Command failed with exit code 1. diff --git a/tests/cases/docker/office-ui-fabric/Dockerfile b/tests/cases/docker/office-ui-fabric/Dockerfile index 718289fabe3..e31dc713ec2 100644 --- a/tests/cases/docker/office-ui-fabric/Dockerfile +++ b/tests/cases/docker/office-ui-fabric/Dockerfile @@ -1,20 +1,21 @@ FROM node:current -RUN npm install -g @microsoft/rush +RUN npm install -g yarn lerna RUN git clone https://github.com/OfficeDev/office-ui-fabric-react.git /office-ui-fabric-react WORKDIR /office-ui-fabric-react RUN git pull -RUN rush update +COPY --from=typescript/typescript /typescript/typescript-*.tgz typescript.tgz +# Sync up all TS versions used internally to the new one WORKDIR /office-ui-fabric-react/scripts -# Sync up all TS versions used internally so they're all linked from a known location -RUN rush add -p "typescript@3.5.1" --exact --dev -m -# Relink installed TSes to built TS -WORKDIR /office-ui-fabric-react/common/temp/node_modules/.registry.npmjs.org/typescript/3.5.1/node_modules -RUN rm -rf typescript -COPY --from=typescript/typescript /typescript/typescript-*.tgz /typescript.tgz -RUN mkdir /typescript -RUN tar -xzvf /typescript.tgz -C /typescript -RUN ln -s /typescript/package ./typescript -RUN npm i -g /typescript.tgz +RUN yarn add typescript@../typescript.tgz --exact --dev --ignore-scripts +WORKDIR /office-ui-fabric-react/packages/tsx-editor +RUN yarn add typescript@../../typescript.tgz --exact --ignore-scripts +WORKDIR /office-ui-fabric-react/packages/migration +RUN yarn add typescript@../../typescript.tgz --exact --ignore-scripts +WORKDIR /office-ui-fabric-react/apps/vr-tests +RUN yarn add typescript@../../typescript.tgz --exact --ignore-scripts +WORKDIR /office-ui-fabric-react/apps/todo-app +RUN yarn add typescript@../../typescript.tgz --exact --ignore-scripts WORKDIR /office-ui-fabric-react -ENTRYPOINT [ "rush" ] -CMD [ "rebuild", "--parallelism", "1" ] \ No newline at end of file +RUN yarn +ENTRYPOINT [ "lerna" ] +CMD [ "run", "build", "--stream", "--concurrency", "1", "--", "--production", "--lint" ] \ No newline at end of file diff --git a/tests/cases/docker/vscode/Dockerfile b/tests/cases/docker/vscode/Dockerfile index d20e2e8d622..b0ece263d54 100644 --- a/tests/cases/docker/vscode/Dockerfile +++ b/tests/cases/docker/vscode/Dockerfile @@ -1,4 +1,4 @@ -# vscode only supports node 8 :( +# vscode only supports older node FROM node:10 RUN apt-get update RUN apt-get install libsecret-1-dev libx11-dev libxkbfile-dev -y @@ -7,12 +7,12 @@ RUN git clone https://github.com/microsoft/vscode.git /vscode WORKDIR /vscode RUN git pull COPY --from=typescript/typescript /typescript/typescript-*.tgz /typescript.tgz -RUN mkdir /typescript -RUN tar -xzvf /typescript.tgz -C /typescript WORKDIR /vscode/build -RUN yarn add typescript@/typescript/package +RUN yarn add typescript@/typescript.tgz +WORKDIR /vscode/extensions +RUN yarn add typescript@/typescript.tgz WORKDIR /vscode -RUN yarn add typescript@/typescript/package +RUN yarn add typescript@/typescript.tgz RUN yarn ENTRYPOINT [ "yarn" ] # Build diff --git a/tests/cases/user/prettier/prettier b/tests/cases/user/prettier/prettier index 7f938c71ffd..1e471a00796 160000 --- a/tests/cases/user/prettier/prettier +++ b/tests/cases/user/prettier/prettier @@ -1 +1 @@ -Subproject commit 7f938c71ffda293eb1b69adf8bd12b7c11f9113b +Subproject commit 1e471a007968b7490563b91ed6909ae6046f3fe8 From 395d1515eeefe5f52aab8a1365824bd0eba49215 Mon Sep 17 00:00:00 2001 From: "Salisbury, Tom" Date: Thu, 18 Jul 2019 12:32:43 +0100 Subject: [PATCH 048/151] #32458 stop ES5 __values with no Symbol.iterator getting stuck in loop --- src/compiler/factory.ts | 7 +- src/testRunner/tsconfig.json | 1 + src/testRunner/unittests/evaluation/forOf.ts | 119 ++++++++++++++++++ tests/baselines/reference/ES5For-of33.js | 7 +- tests/baselines/reference/ES5For-of33.js.map | 2 +- .../reference/ES5For-of33.sourcemap.txt | 63 +++++----- tests/baselines/reference/ES5For-of34.js | 7 +- tests/baselines/reference/ES5For-of34.js.map | 2 +- .../reference/ES5For-of34.sourcemap.txt | 95 +++++++------- tests/baselines/reference/ES5For-of35.js | 7 +- tests/baselines/reference/ES5For-of35.js.map | 2 +- .../reference/ES5For-of35.sourcemap.txt | 69 +++++----- tests/baselines/reference/ES5For-of36.js | 7 +- tests/baselines/reference/ES5For-of36.js.map | 2 +- .../reference/ES5For-of36.sourcemap.txt | 69 +++++----- tests/baselines/reference/ES5For-of37.js | 7 +- ...blockScopedBindingsInDownlevelGenerator.js | 7 +- ...mitter.asyncGenerators.classMethods.es5.js | 14 ++- ...syncGenerators.functionDeclarations.es5.js | 14 ++- ...asyncGenerators.functionExpressions.es5.js | 14 ++- ...syncGenerators.objectLiteralMethods.es5.js | 14 ++- ...eclarationBindingPatterns01_ES5iterable.js | 7 +- 22 files changed, 338 insertions(+), 198 deletions(-) create mode 100644 src/testRunner/unittests/evaluation/forOf.ts diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 1f0294423a5..82b4a3fb59f 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3636,15 +3636,16 @@ namespace ts { name: "typescript:values", scoped: false, text: ` - var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; + var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); };` }; diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 659dd426b79..d69feffb787 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -75,6 +75,7 @@ "unittests/evaluation/asyncGenerator.ts", "unittests/evaluation/awaiter.ts", "unittests/evaluation/forAwaitOf.ts", + "unittests/evaluation/forOf.ts", "unittests/evaluation/objectRest.ts", "unittests/services/cancellableLanguageServiceOperations.ts", "unittests/services/colorization.ts", diff --git a/src/testRunner/unittests/evaluation/forOf.ts b/src/testRunner/unittests/evaluation/forOf.ts new file mode 100644 index 00000000000..3d9352cf926 --- /dev/null +++ b/src/testRunner/unittests/evaluation/forOf.ts @@ -0,0 +1,119 @@ +describe("unittests:: evaluation:: forOfEvaluation", () => { + it("es5 over a array with no Symbol", () => { + const result = evaluator.evaluateTypeScript(` + Symbol = undefined; + export var output = []; + export function main() { + let x = [1,2,3]; + + for (let value of x) { + output.push(value); + } + } + `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + result.main(); + + assert.strictEqual(result.output[0], 1); + assert.strictEqual(result.output[1], 2); + assert.strictEqual(result.output[2], 3); + + }); + + it("es5 over a string with no Symbol", () => { + const result = evaluator.evaluateTypeScript(` + Symbol = undefined; + export var output = []; + export function main() { + let x = "hello"; + + for (let value of x) { + output.push(value); + } + } + `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + result.main(); + + assert.strictEqual(result.output[0], "h"); + assert.strictEqual(result.output[1], "e"); + assert.strictEqual(result.output[2], "l"); + assert.strictEqual(result.output[3], "l"); + assert.strictEqual(result.output[4], "o"); + }); + + it("es5 over undefined with no Symbol", () => { + const result = evaluator.evaluateTypeScript(` + Symbol = undefined; + export function main() { + let x = undefined; + + for (let value of x) { + } + } + `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + assert.throws(() => result.main(), "Symbol.iterator is not defined"); + }); + + it("es5 over undefined with Symbol", () => { + const result = evaluator.evaluateTypeScript(` + export function main() { + let x = undefined; + + for (let value of x) { + } + } + `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + assert.throws(() => result.main(), "undefined is not iterable (cannot read property Symbol(Symbol.iterator))"); + }); + + it("es5 over object with no Symbol.iterator with no Symbol", () => { + const result = evaluator.evaluateTypeScript(` + Symbol = undefined; + export function main() { + let x = {} as any; + + for (let value of x) { + } + } + `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + assert.throws(() => result.main(), "Symbol.iterator is not defined"); + }); + + it("es5 over object with no Symbol.iterator with Symbol", () => { + const result = evaluator.evaluateTypeScript(` + export function main() { + let x = {} as any; + + for (let value of x) { + } + } + `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + assert.throws(() => result.main(), "Object not iterable"); + }); + + it("es5 over object with Symbol.iterator", () => { + const result = evaluator.evaluateTypeScript(` + export var output = []; + export function main() { + let thing : any = {}; + thing[Symbol.iterator] = () => { + let i = 0; + return { next() { i++; return this; }, value: i, done: i < 10 }; + }; + + for (let value of thing) + { + output.push(value) + } + + }`, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + + result.main(); + }); + +}); \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of33.js b/tests/baselines/reference/ES5For-of33.js index 8a7bacbf52d..900f32b6407 100644 --- a/tests/baselines/reference/ES5For-of33.js +++ b/tests/baselines/reference/ES5For-of33.js @@ -4,15 +4,16 @@ for (var v of ['a', 'b', 'c']) { } //// [ES5For-of33.js] -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var e_1, _a; try { diff --git a/tests/baselines/reference/ES5For-of33.js.map b/tests/baselines/reference/ES5For-of33.js.map index c2a28ecec79..368ef47a3f5 100644 --- a/tests/baselines/reference/ES5For-of33.js.map +++ b/tests/baselines/reference/ES5For-of33.js.map @@ -1,2 +1,2 @@ //// [ES5For-of33.js.map] -{"version":3,"file":"ES5For-of33.js","sourceRoot":"","sources":["ES5For-of33.ts"],"names":[],"mappings":";;;;;;;;;;;;IAAA,KAAc,IAAA,KAAA,SAAA,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA,gBAAA,4BAAE;QAA1B,IAAI,CAAC,WAAA;QACN,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;KAClB"} \ No newline at end of file +{"version":3,"file":"ES5For-of33.js","sourceRoot":"","sources":["ES5For-of33.ts"],"names":[],"mappings":";;;;;;;;;;;;;IAAA,KAAc,IAAA,KAAA,SAAA,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA,gBAAA,4BAAE;QAA1B,IAAI,CAAC,WAAA;QACN,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;KAClB"} \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of33.sourcemap.txt b/tests/baselines/reference/ES5For-of33.sourcemap.txt index 8438d558c74..f6be2e8fb11 100644 --- a/tests/baselines/reference/ES5For-of33.sourcemap.txt +++ b/tests/baselines/reference/ES5For-of33.sourcemap.txt @@ -8,15 +8,16 @@ sources: ES5For-of33.ts emittedFile:tests/cases/conformance/statements/for-ofStatements/ES5For-of33.js sourceFile:ES5For-of33.ts ------------------------------------------------------------------- ->>>var __values = (this && this.__values) || function (o) { ->>> var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +>>>var __values = (this && this.__values) || function(o) { +>>> var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; >>> if (m) return m.call(o); ->>> return { +>>> if (o && typeof o.length === "number") return { >>> next: function () { >>> if (o && i >= o.length) o = void 0; >>> return { value: o && o[i++], done: !o }; >>> } >>> }; +>>> throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); >>>}; >>>var e_1, _a; >>>try { @@ -51,21 +52,21 @@ sourceFile:ES5For-of33.ts 13> 14> 15> ) -1 >Emitted(13, 5) Source(1, 1) + SourceIndex(0) -2 >Emitted(13, 10) Source(1, 15) + SourceIndex(0) -3 >Emitted(13, 14) Source(1, 15) + SourceIndex(0) -4 >Emitted(13, 19) Source(1, 15) + SourceIndex(0) -5 >Emitted(13, 28) Source(1, 15) + SourceIndex(0) -6 >Emitted(13, 29) Source(1, 16) + SourceIndex(0) -7 >Emitted(13, 32) Source(1, 19) + SourceIndex(0) -8 >Emitted(13, 34) Source(1, 21) + SourceIndex(0) -9 >Emitted(13, 37) Source(1, 24) + SourceIndex(0) -10>Emitted(13, 39) Source(1, 26) + SourceIndex(0) -11>Emitted(13, 42) Source(1, 29) + SourceIndex(0) -12>Emitted(13, 43) Source(1, 30) + SourceIndex(0) -13>Emitted(13, 44) Source(1, 30) + SourceIndex(0) -14>Emitted(13, 60) Source(1, 30) + SourceIndex(0) -15>Emitted(13, 88) Source(1, 32) + SourceIndex(0) +1 >Emitted(14, 5) Source(1, 1) + SourceIndex(0) +2 >Emitted(14, 10) Source(1, 15) + SourceIndex(0) +3 >Emitted(14, 14) Source(1, 15) + SourceIndex(0) +4 >Emitted(14, 19) Source(1, 15) + SourceIndex(0) +5 >Emitted(14, 28) Source(1, 15) + SourceIndex(0) +6 >Emitted(14, 29) Source(1, 16) + SourceIndex(0) +7 >Emitted(14, 32) Source(1, 19) + SourceIndex(0) +8 >Emitted(14, 34) Source(1, 21) + SourceIndex(0) +9 >Emitted(14, 37) Source(1, 24) + SourceIndex(0) +10>Emitted(14, 39) Source(1, 26) + SourceIndex(0) +11>Emitted(14, 42) Source(1, 29) + SourceIndex(0) +12>Emitted(14, 43) Source(1, 30) + SourceIndex(0) +13>Emitted(14, 44) Source(1, 30) + SourceIndex(0) +14>Emitted(14, 60) Source(1, 30) + SourceIndex(0) +15>Emitted(14, 88) Source(1, 32) + SourceIndex(0) --- >>> var v = _c.value; 1 >^^^^^^^^ @@ -76,10 +77,10 @@ sourceFile:ES5For-of33.ts 2 > var 3 > v 4 > -1 >Emitted(14, 9) Source(1, 6) + SourceIndex(0) -2 >Emitted(14, 13) Source(1, 10) + SourceIndex(0) -3 >Emitted(14, 14) Source(1, 11) + SourceIndex(0) -4 >Emitted(14, 25) Source(1, 11) + SourceIndex(0) +1 >Emitted(15, 9) Source(1, 6) + SourceIndex(0) +2 >Emitted(15, 13) Source(1, 10) + SourceIndex(0) +3 >Emitted(15, 14) Source(1, 11) + SourceIndex(0) +4 >Emitted(15, 25) Source(1, 11) + SourceIndex(0) --- >>> console.log(v); 1 >^^^^^^^^ @@ -99,20 +100,20 @@ sourceFile:ES5For-of33.ts 6 > v 7 > ) 8 > ; -1 >Emitted(15, 9) Source(2, 5) + SourceIndex(0) -2 >Emitted(15, 16) Source(2, 12) + SourceIndex(0) -3 >Emitted(15, 17) Source(2, 13) + SourceIndex(0) -4 >Emitted(15, 20) Source(2, 16) + SourceIndex(0) -5 >Emitted(15, 21) Source(2, 17) + SourceIndex(0) -6 >Emitted(15, 22) Source(2, 18) + SourceIndex(0) -7 >Emitted(15, 23) Source(2, 19) + SourceIndex(0) -8 >Emitted(15, 24) Source(2, 20) + SourceIndex(0) +1 >Emitted(16, 9) Source(2, 5) + SourceIndex(0) +2 >Emitted(16, 16) Source(2, 12) + SourceIndex(0) +3 >Emitted(16, 17) Source(2, 13) + SourceIndex(0) +4 >Emitted(16, 20) Source(2, 16) + SourceIndex(0) +5 >Emitted(16, 21) Source(2, 17) + SourceIndex(0) +6 >Emitted(16, 22) Source(2, 18) + SourceIndex(0) +7 >Emitted(16, 23) Source(2, 19) + SourceIndex(0) +8 >Emitted(16, 24) Source(2, 20) + SourceIndex(0) --- >>> } 1 >^^^^^ 1 > >} -1 >Emitted(16, 6) Source(3, 2) + SourceIndex(0) +1 >Emitted(17, 6) Source(3, 2) + SourceIndex(0) --- >>>} >>>catch (e_1_1) { e_1 = { error: e_1_1 }; } diff --git a/tests/baselines/reference/ES5For-of34.js b/tests/baselines/reference/ES5For-of34.js index 821cec60ee1..d4ab664d009 100644 --- a/tests/baselines/reference/ES5For-of34.js +++ b/tests/baselines/reference/ES5For-of34.js @@ -7,15 +7,16 @@ for (foo().x of ['a', 'b', 'c']) { } //// [ES5For-of34.js] -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var e_1, _a; function foo() { diff --git a/tests/baselines/reference/ES5For-of34.js.map b/tests/baselines/reference/ES5For-of34.js.map index 6bf7fd0baed..9535e73615c 100644 --- a/tests/baselines/reference/ES5For-of34.js.map +++ b/tests/baselines/reference/ES5For-of34.js.map @@ -1,2 +1,2 @@ //// [ES5For-of34.js.map] -{"version":3,"file":"ES5For-of34.js","sourceRoot":"","sources":["ES5For-of34.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,SAAS,GAAG;IACR,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACpB,CAAC;;IACD,KAAgB,IAAA,KAAA,SAAA,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA,gBAAA,4BAAE;QAA5B,GAAG,EAAE,CAAC,CAAC,WAAA;QACR,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC;KACnB"} \ No newline at end of file +{"version":3,"file":"ES5For-of34.js","sourceRoot":"","sources":["ES5For-of34.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,SAAS,GAAG;IACR,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACpB,CAAC;;IACD,KAAgB,IAAA,KAAA,SAAA,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA,gBAAA,4BAAE;QAA5B,GAAG,EAAE,CAAC,CAAC,WAAA;QACR,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC;KACnB"} \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of34.sourcemap.txt b/tests/baselines/reference/ES5For-of34.sourcemap.txt index 06e93f578e2..e64aa5cdb8c 100644 --- a/tests/baselines/reference/ES5For-of34.sourcemap.txt +++ b/tests/baselines/reference/ES5For-of34.sourcemap.txt @@ -8,15 +8,16 @@ sources: ES5For-of34.ts emittedFile:tests/cases/conformance/statements/for-ofStatements/ES5For-of34.js sourceFile:ES5For-of34.ts ------------------------------------------------------------------- ->>>var __values = (this && this.__values) || function (o) { ->>> var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +>>>var __values = (this && this.__values) || function(o) { +>>> var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; >>> if (m) return m.call(o); ->>> return { +>>> if (o && typeof o.length === "number") return { >>> next: function () { >>> if (o && i >= o.length) o = void 0; >>> return { value: o && o[i++], done: !o }; >>> } >>> }; +>>> throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); >>>}; >>>var e_1, _a; >>>function foo() { @@ -27,9 +28,9 @@ sourceFile:ES5For-of34.ts 1 > 2 >function 3 > foo -1 >Emitted(12, 1) Source(1, 1) + SourceIndex(0) -2 >Emitted(12, 10) Source(1, 10) + SourceIndex(0) -3 >Emitted(12, 13) Source(1, 13) + SourceIndex(0) +1 >Emitted(13, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(13, 10) Source(1, 10) + SourceIndex(0) +3 >Emitted(13, 13) Source(1, 13) + SourceIndex(0) --- >>> return { x: 0 }; 1->^^^^ @@ -49,14 +50,14 @@ sourceFile:ES5For-of34.ts 6 > 0 7 > } 8 > ; -1->Emitted(13, 5) Source(2, 5) + SourceIndex(0) -2 >Emitted(13, 12) Source(2, 12) + SourceIndex(0) -3 >Emitted(13, 14) Source(2, 14) + SourceIndex(0) -4 >Emitted(13, 15) Source(2, 15) + SourceIndex(0) -5 >Emitted(13, 17) Source(2, 17) + SourceIndex(0) -6 >Emitted(13, 18) Source(2, 18) + SourceIndex(0) -7 >Emitted(13, 20) Source(2, 20) + SourceIndex(0) -8 >Emitted(13, 21) Source(2, 21) + SourceIndex(0) +1->Emitted(14, 5) Source(2, 5) + SourceIndex(0) +2 >Emitted(14, 12) Source(2, 12) + SourceIndex(0) +3 >Emitted(14, 14) Source(2, 14) + SourceIndex(0) +4 >Emitted(14, 15) Source(2, 15) + SourceIndex(0) +5 >Emitted(14, 17) Source(2, 17) + SourceIndex(0) +6 >Emitted(14, 18) Source(2, 18) + SourceIndex(0) +7 >Emitted(14, 20) Source(2, 20) + SourceIndex(0) +8 >Emitted(14, 21) Source(2, 21) + SourceIndex(0) --- >>>} 1 > @@ -65,8 +66,8 @@ sourceFile:ES5For-of34.ts 1 > > 2 >} -1 >Emitted(14, 1) Source(3, 1) + SourceIndex(0) -2 >Emitted(14, 2) Source(3, 2) + SourceIndex(0) +1 >Emitted(15, 1) Source(3, 1) + SourceIndex(0) +2 >Emitted(15, 2) Source(3, 2) + SourceIndex(0) --- >>>try { >>> for (var _b = __values(['a', 'b', 'c']), _c = _b.next(); !_c.done; _c = _b.next()) { @@ -101,21 +102,21 @@ sourceFile:ES5For-of34.ts 13> 14> 15> ) -1->Emitted(16, 5) Source(4, 1) + SourceIndex(0) -2 >Emitted(16, 10) Source(4, 17) + SourceIndex(0) -3 >Emitted(16, 14) Source(4, 17) + SourceIndex(0) -4 >Emitted(16, 19) Source(4, 17) + SourceIndex(0) -5 >Emitted(16, 28) Source(4, 17) + SourceIndex(0) -6 >Emitted(16, 29) Source(4, 18) + SourceIndex(0) -7 >Emitted(16, 32) Source(4, 21) + SourceIndex(0) -8 >Emitted(16, 34) Source(4, 23) + SourceIndex(0) -9 >Emitted(16, 37) Source(4, 26) + SourceIndex(0) -10>Emitted(16, 39) Source(4, 28) + SourceIndex(0) -11>Emitted(16, 42) Source(4, 31) + SourceIndex(0) -12>Emitted(16, 43) Source(4, 32) + SourceIndex(0) -13>Emitted(16, 44) Source(4, 32) + SourceIndex(0) -14>Emitted(16, 60) Source(4, 32) + SourceIndex(0) -15>Emitted(16, 88) Source(4, 34) + SourceIndex(0) +1->Emitted(17, 5) Source(4, 1) + SourceIndex(0) +2 >Emitted(17, 10) Source(4, 17) + SourceIndex(0) +3 >Emitted(17, 14) Source(4, 17) + SourceIndex(0) +4 >Emitted(17, 19) Source(4, 17) + SourceIndex(0) +5 >Emitted(17, 28) Source(4, 17) + SourceIndex(0) +6 >Emitted(17, 29) Source(4, 18) + SourceIndex(0) +7 >Emitted(17, 32) Source(4, 21) + SourceIndex(0) +8 >Emitted(17, 34) Source(4, 23) + SourceIndex(0) +9 >Emitted(17, 37) Source(4, 26) + SourceIndex(0) +10>Emitted(17, 39) Source(4, 28) + SourceIndex(0) +11>Emitted(17, 42) Source(4, 31) + SourceIndex(0) +12>Emitted(17, 43) Source(4, 32) + SourceIndex(0) +13>Emitted(17, 44) Source(4, 32) + SourceIndex(0) +14>Emitted(17, 60) Source(4, 32) + SourceIndex(0) +15>Emitted(17, 88) Source(4, 34) + SourceIndex(0) --- >>> foo().x = _c.value; 1 >^^^^^^^^ @@ -130,12 +131,12 @@ sourceFile:ES5For-of34.ts 4 > . 5 > x 6 > -1 >Emitted(17, 9) Source(4, 6) + SourceIndex(0) -2 >Emitted(17, 12) Source(4, 9) + SourceIndex(0) -3 >Emitted(17, 14) Source(4, 11) + SourceIndex(0) -4 >Emitted(17, 15) Source(4, 12) + SourceIndex(0) -5 >Emitted(17, 16) Source(4, 13) + SourceIndex(0) -6 >Emitted(17, 27) Source(4, 13) + SourceIndex(0) +1 >Emitted(18, 9) Source(4, 6) + SourceIndex(0) +2 >Emitted(18, 12) Source(4, 9) + SourceIndex(0) +3 >Emitted(18, 14) Source(4, 11) + SourceIndex(0) +4 >Emitted(18, 15) Source(4, 12) + SourceIndex(0) +5 >Emitted(18, 16) Source(4, 13) + SourceIndex(0) +6 >Emitted(18, 27) Source(4, 13) + SourceIndex(0) --- >>> var p = foo().x; 1 >^^^^^^^^ @@ -157,21 +158,21 @@ sourceFile:ES5For-of34.ts 7 > . 8 > x 9 > ; -1 >Emitted(18, 9) Source(5, 5) + SourceIndex(0) -2 >Emitted(18, 13) Source(5, 9) + SourceIndex(0) -3 >Emitted(18, 14) Source(5, 10) + SourceIndex(0) -4 >Emitted(18, 17) Source(5, 13) + SourceIndex(0) -5 >Emitted(18, 20) Source(5, 16) + SourceIndex(0) -6 >Emitted(18, 22) Source(5, 18) + SourceIndex(0) -7 >Emitted(18, 23) Source(5, 19) + SourceIndex(0) -8 >Emitted(18, 24) Source(5, 20) + SourceIndex(0) -9 >Emitted(18, 25) Source(5, 21) + SourceIndex(0) +1 >Emitted(19, 9) Source(5, 5) + SourceIndex(0) +2 >Emitted(19, 13) Source(5, 9) + SourceIndex(0) +3 >Emitted(19, 14) Source(5, 10) + SourceIndex(0) +4 >Emitted(19, 17) Source(5, 13) + SourceIndex(0) +5 >Emitted(19, 20) Source(5, 16) + SourceIndex(0) +6 >Emitted(19, 22) Source(5, 18) + SourceIndex(0) +7 >Emitted(19, 23) Source(5, 19) + SourceIndex(0) +8 >Emitted(19, 24) Source(5, 20) + SourceIndex(0) +9 >Emitted(19, 25) Source(5, 21) + SourceIndex(0) --- >>> } 1 >^^^^^ 1 > >} -1 >Emitted(19, 6) Source(6, 2) + SourceIndex(0) +1 >Emitted(20, 6) Source(6, 2) + SourceIndex(0) --- >>>} >>>catch (e_1_1) { e_1 = { error: e_1_1 }; } diff --git a/tests/baselines/reference/ES5For-of35.js b/tests/baselines/reference/ES5For-of35.js index 608ce967479..1158ae5ede1 100644 --- a/tests/baselines/reference/ES5For-of35.js +++ b/tests/baselines/reference/ES5For-of35.js @@ -5,15 +5,16 @@ for (const {x: a = 0, y: b = 1} of [2, 3]) { } //// [ES5For-of35.js] -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var e_1, _a; try { diff --git a/tests/baselines/reference/ES5For-of35.js.map b/tests/baselines/reference/ES5For-of35.js.map index ca243e5bde5..ff69685616b 100644 --- a/tests/baselines/reference/ES5For-of35.js.map +++ b/tests/baselines/reference/ES5For-of35.js.map @@ -1,2 +1,2 @@ //// [ES5For-of35.js.map] -{"version":3,"file":"ES5For-of35.js","sourceRoot":"","sources":["ES5For-of35.ts"],"names":[],"mappings":";;;;;;;;;;;;IAAA,KAAmC,IAAA,KAAA,SAAA,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA,gBAAA,4BAAE;QAAhC,IAAA,aAAoB,EAAnB,SAAQ,EAAR,0BAAQ,EAAE,SAAQ,EAAR,0BAAQ;QAC1B,CAAC,CAAC;QACF,CAAC,CAAC;KACL"} \ No newline at end of file +{"version":3,"file":"ES5For-of35.js","sourceRoot":"","sources":["ES5For-of35.ts"],"names":[],"mappings":";;;;;;;;;;;;;IAAA,KAAmC,IAAA,KAAA,SAAA,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA,gBAAA,4BAAE;QAAhC,IAAA,aAAoB,EAAnB,SAAQ,EAAR,0BAAQ,EAAE,SAAQ,EAAR,0BAAQ;QAC1B,CAAC,CAAC;QACF,CAAC,CAAC;KACL"} \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of35.sourcemap.txt b/tests/baselines/reference/ES5For-of35.sourcemap.txt index 907fc3ce690..1cabb7af3b6 100644 --- a/tests/baselines/reference/ES5For-of35.sourcemap.txt +++ b/tests/baselines/reference/ES5For-of35.sourcemap.txt @@ -8,15 +8,16 @@ sources: ES5For-of35.ts emittedFile:tests/cases/conformance/statements/for-ofStatements/ES5For-of35.js sourceFile:ES5For-of35.ts ------------------------------------------------------------------- ->>>var __values = (this && this.__values) || function (o) { ->>> var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +>>>var __values = (this && this.__values) || function(o) { +>>> var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; >>> if (m) return m.call(o); ->>> return { +>>> if (o && typeof o.length === "number") return { >>> next: function () { >>> if (o && i >= o.length) o = void 0; >>> return { value: o && o[i++], done: !o }; >>> } >>> }; +>>> throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); >>>}; >>>var e_1, _a; >>>try { @@ -48,19 +49,19 @@ sourceFile:ES5For-of35.ts 11> 12> 13> ) -1 >Emitted(13, 5) Source(1, 1) + SourceIndex(0) -2 >Emitted(13, 10) Source(1, 36) + SourceIndex(0) -3 >Emitted(13, 14) Source(1, 36) + SourceIndex(0) -4 >Emitted(13, 19) Source(1, 36) + SourceIndex(0) -5 >Emitted(13, 28) Source(1, 36) + SourceIndex(0) -6 >Emitted(13, 29) Source(1, 37) + SourceIndex(0) -7 >Emitted(13, 30) Source(1, 38) + SourceIndex(0) -8 >Emitted(13, 32) Source(1, 40) + SourceIndex(0) -9 >Emitted(13, 33) Source(1, 41) + SourceIndex(0) -10>Emitted(13, 34) Source(1, 42) + SourceIndex(0) -11>Emitted(13, 35) Source(1, 42) + SourceIndex(0) -12>Emitted(13, 51) Source(1, 42) + SourceIndex(0) -13>Emitted(13, 79) Source(1, 44) + SourceIndex(0) +1 >Emitted(14, 5) Source(1, 1) + SourceIndex(0) +2 >Emitted(14, 10) Source(1, 36) + SourceIndex(0) +3 >Emitted(14, 14) Source(1, 36) + SourceIndex(0) +4 >Emitted(14, 19) Source(1, 36) + SourceIndex(0) +5 >Emitted(14, 28) Source(1, 36) + SourceIndex(0) +6 >Emitted(14, 29) Source(1, 37) + SourceIndex(0) +7 >Emitted(14, 30) Source(1, 38) + SourceIndex(0) +8 >Emitted(14, 32) Source(1, 40) + SourceIndex(0) +9 >Emitted(14, 33) Source(1, 41) + SourceIndex(0) +10>Emitted(14, 34) Source(1, 42) + SourceIndex(0) +11>Emitted(14, 35) Source(1, 42) + SourceIndex(0) +12>Emitted(14, 51) Source(1, 42) + SourceIndex(0) +13>Emitted(14, 79) Source(1, 44) + SourceIndex(0) --- >>> var _d = _c.value, _e = _d.x, a = _e === void 0 ? 0 : _e, _f = _d.y, b = _f === void 0 ? 1 : _f; 1->^^^^^^^^ @@ -85,17 +86,17 @@ sourceFile:ES5For-of35.ts 9 > y: b = 1 10> 11> y: b = 1 -1->Emitted(14, 9) Source(1, 12) + SourceIndex(0) -2 >Emitted(14, 13) Source(1, 12) + SourceIndex(0) -3 >Emitted(14, 26) Source(1, 32) + SourceIndex(0) -4 >Emitted(14, 28) Source(1, 13) + SourceIndex(0) -5 >Emitted(14, 37) Source(1, 21) + SourceIndex(0) -6 >Emitted(14, 39) Source(1, 13) + SourceIndex(0) -7 >Emitted(14, 65) Source(1, 21) + SourceIndex(0) -8 >Emitted(14, 67) Source(1, 23) + SourceIndex(0) -9 >Emitted(14, 76) Source(1, 31) + SourceIndex(0) -10>Emitted(14, 78) Source(1, 23) + SourceIndex(0) -11>Emitted(14, 104) Source(1, 31) + SourceIndex(0) +1->Emitted(15, 9) Source(1, 12) + SourceIndex(0) +2 >Emitted(15, 13) Source(1, 12) + SourceIndex(0) +3 >Emitted(15, 26) Source(1, 32) + SourceIndex(0) +4 >Emitted(15, 28) Source(1, 13) + SourceIndex(0) +5 >Emitted(15, 37) Source(1, 21) + SourceIndex(0) +6 >Emitted(15, 39) Source(1, 13) + SourceIndex(0) +7 >Emitted(15, 65) Source(1, 21) + SourceIndex(0) +8 >Emitted(15, 67) Source(1, 23) + SourceIndex(0) +9 >Emitted(15, 76) Source(1, 31) + SourceIndex(0) +10>Emitted(15, 78) Source(1, 23) + SourceIndex(0) +11>Emitted(15, 104) Source(1, 31) + SourceIndex(0) --- >>> a; 1 >^^^^^^^^ @@ -106,9 +107,9 @@ sourceFile:ES5For-of35.ts > 2 > a 3 > ; -1 >Emitted(15, 9) Source(2, 5) + SourceIndex(0) -2 >Emitted(15, 10) Source(2, 6) + SourceIndex(0) -3 >Emitted(15, 11) Source(2, 7) + SourceIndex(0) +1 >Emitted(16, 9) Source(2, 5) + SourceIndex(0) +2 >Emitted(16, 10) Source(2, 6) + SourceIndex(0) +3 >Emitted(16, 11) Source(2, 7) + SourceIndex(0) --- >>> b; 1->^^^^^^^^ @@ -118,15 +119,15 @@ sourceFile:ES5For-of35.ts > 2 > b 3 > ; -1->Emitted(16, 9) Source(3, 5) + SourceIndex(0) -2 >Emitted(16, 10) Source(3, 6) + SourceIndex(0) -3 >Emitted(16, 11) Source(3, 7) + SourceIndex(0) +1->Emitted(17, 9) Source(3, 5) + SourceIndex(0) +2 >Emitted(17, 10) Source(3, 6) + SourceIndex(0) +3 >Emitted(17, 11) Source(3, 7) + SourceIndex(0) --- >>> } 1 >^^^^^ 1 > >} -1 >Emitted(17, 6) Source(4, 2) + SourceIndex(0) +1 >Emitted(18, 6) Source(4, 2) + SourceIndex(0) --- >>>} >>>catch (e_1_1) { e_1 = { error: e_1_1 }; } diff --git a/tests/baselines/reference/ES5For-of36.js b/tests/baselines/reference/ES5For-of36.js index 5d53b241466..f08a178256d 100644 --- a/tests/baselines/reference/ES5For-of36.js +++ b/tests/baselines/reference/ES5For-of36.js @@ -5,15 +5,16 @@ for (let [a = 0, b = 1] of [2, 3]) { } //// [ES5For-of36.js] -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; diff --git a/tests/baselines/reference/ES5For-of36.js.map b/tests/baselines/reference/ES5For-of36.js.map index 09fdb4fd820..9ea2aa31df2 100644 --- a/tests/baselines/reference/ES5For-of36.js.map +++ b/tests/baselines/reference/ES5For-of36.js.map @@ -1,2 +1,2 @@ //// [ES5For-of36.js.map] -{"version":3,"file":"ES5For-of36.js","sourceRoot":"","sources":["ES5For-of36.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA,KAA2B,IAAA,KAAA,SAAA,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA,gBAAA,4BAAE;QAA1B,IAAA,wBAAc,EAAb,UAAK,EAAL,0BAAK,EAAE,UAAK,EAAL,0BAAK;QAClB,CAAC,CAAC;QACF,CAAC,CAAC;KACL"} \ No newline at end of file +{"version":3,"file":"ES5For-of36.js","sourceRoot":"","sources":["ES5For-of36.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA,KAA2B,IAAA,KAAA,SAAA,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA,gBAAA,4BAAE;QAA1B,IAAA,wBAAc,EAAb,UAAK,EAAL,0BAAK,EAAE,UAAK,EAAL,0BAAK;QAClB,CAAC,CAAC;QACF,CAAC,CAAC;KACL"} \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of36.sourcemap.txt b/tests/baselines/reference/ES5For-of36.sourcemap.txt index c3ac87f51ca..b1977e55d81 100644 --- a/tests/baselines/reference/ES5For-of36.sourcemap.txt +++ b/tests/baselines/reference/ES5For-of36.sourcemap.txt @@ -8,15 +8,16 @@ sources: ES5For-of36.ts emittedFile:tests/cases/conformance/statements/for-ofStatements/ES5For-of36.js sourceFile:ES5For-of36.ts ------------------------------------------------------------------- ->>>var __values = (this && this.__values) || function (o) { ->>> var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +>>>var __values = (this && this.__values) || function(o) { +>>> var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; >>> if (m) return m.call(o); ->>> return { +>>> if (o && typeof o.length === "number") return { >>> next: function () { >>> if (o && i >= o.length) o = void 0; >>> return { value: o && o[i++], done: !o }; >>> } >>> }; +>>> throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); >>>}; >>>var __read = (this && this.__read) || function (o, n) { >>> var m = typeof Symbol === "function" && o[Symbol.iterator]; @@ -64,19 +65,19 @@ sourceFile:ES5For-of36.ts 11> 12> 13> ) -1 >Emitted(29, 5) Source(1, 1) + SourceIndex(0) -2 >Emitted(29, 10) Source(1, 28) + SourceIndex(0) -3 >Emitted(29, 14) Source(1, 28) + SourceIndex(0) -4 >Emitted(29, 19) Source(1, 28) + SourceIndex(0) -5 >Emitted(29, 28) Source(1, 28) + SourceIndex(0) -6 >Emitted(29, 29) Source(1, 29) + SourceIndex(0) -7 >Emitted(29, 30) Source(1, 30) + SourceIndex(0) -8 >Emitted(29, 32) Source(1, 32) + SourceIndex(0) -9 >Emitted(29, 33) Source(1, 33) + SourceIndex(0) -10>Emitted(29, 34) Source(1, 34) + SourceIndex(0) -11>Emitted(29, 35) Source(1, 34) + SourceIndex(0) -12>Emitted(29, 51) Source(1, 34) + SourceIndex(0) -13>Emitted(29, 79) Source(1, 36) + SourceIndex(0) +1 >Emitted(30, 5) Source(1, 1) + SourceIndex(0) +2 >Emitted(30, 10) Source(1, 28) + SourceIndex(0) +3 >Emitted(30, 14) Source(1, 28) + SourceIndex(0) +4 >Emitted(30, 19) Source(1, 28) + SourceIndex(0) +5 >Emitted(30, 28) Source(1, 28) + SourceIndex(0) +6 >Emitted(30, 29) Source(1, 29) + SourceIndex(0) +7 >Emitted(30, 30) Source(1, 30) + SourceIndex(0) +8 >Emitted(30, 32) Source(1, 32) + SourceIndex(0) +9 >Emitted(30, 33) Source(1, 33) + SourceIndex(0) +10>Emitted(30, 34) Source(1, 34) + SourceIndex(0) +11>Emitted(30, 35) Source(1, 34) + SourceIndex(0) +12>Emitted(30, 51) Source(1, 34) + SourceIndex(0) +13>Emitted(30, 79) Source(1, 36) + SourceIndex(0) --- >>> var _d = __read(_c.value, 2), _e = _d[0], a = _e === void 0 ? 0 : _e, _f = _d[1], b = _f === void 0 ? 1 : _f; 1->^^^^^^^^ @@ -101,17 +102,17 @@ sourceFile:ES5For-of36.ts 9 > b = 1 10> 11> b = 1 -1->Emitted(30, 9) Source(1, 10) + SourceIndex(0) -2 >Emitted(30, 13) Source(1, 10) + SourceIndex(0) -3 >Emitted(30, 37) Source(1, 24) + SourceIndex(0) -4 >Emitted(30, 39) Source(1, 11) + SourceIndex(0) -5 >Emitted(30, 49) Source(1, 16) + SourceIndex(0) -6 >Emitted(30, 51) Source(1, 11) + SourceIndex(0) -7 >Emitted(30, 77) Source(1, 16) + SourceIndex(0) -8 >Emitted(30, 79) Source(1, 18) + SourceIndex(0) -9 >Emitted(30, 89) Source(1, 23) + SourceIndex(0) -10>Emitted(30, 91) Source(1, 18) + SourceIndex(0) -11>Emitted(30, 117) Source(1, 23) + SourceIndex(0) +1->Emitted(31, 9) Source(1, 10) + SourceIndex(0) +2 >Emitted(31, 13) Source(1, 10) + SourceIndex(0) +3 >Emitted(31, 37) Source(1, 24) + SourceIndex(0) +4 >Emitted(31, 39) Source(1, 11) + SourceIndex(0) +5 >Emitted(31, 49) Source(1, 16) + SourceIndex(0) +6 >Emitted(31, 51) Source(1, 11) + SourceIndex(0) +7 >Emitted(31, 77) Source(1, 16) + SourceIndex(0) +8 >Emitted(31, 79) Source(1, 18) + SourceIndex(0) +9 >Emitted(31, 89) Source(1, 23) + SourceIndex(0) +10>Emitted(31, 91) Source(1, 18) + SourceIndex(0) +11>Emitted(31, 117) Source(1, 23) + SourceIndex(0) --- >>> a; 1 >^^^^^^^^ @@ -122,9 +123,9 @@ sourceFile:ES5For-of36.ts > 2 > a 3 > ; -1 >Emitted(31, 9) Source(2, 5) + SourceIndex(0) -2 >Emitted(31, 10) Source(2, 6) + SourceIndex(0) -3 >Emitted(31, 11) Source(2, 7) + SourceIndex(0) +1 >Emitted(32, 9) Source(2, 5) + SourceIndex(0) +2 >Emitted(32, 10) Source(2, 6) + SourceIndex(0) +3 >Emitted(32, 11) Source(2, 7) + SourceIndex(0) --- >>> b; 1->^^^^^^^^ @@ -134,15 +135,15 @@ sourceFile:ES5For-of36.ts > 2 > b 3 > ; -1->Emitted(32, 9) Source(3, 5) + SourceIndex(0) -2 >Emitted(32, 10) Source(3, 6) + SourceIndex(0) -3 >Emitted(32, 11) Source(3, 7) + SourceIndex(0) +1->Emitted(33, 9) Source(3, 5) + SourceIndex(0) +2 >Emitted(33, 10) Source(3, 6) + SourceIndex(0) +3 >Emitted(33, 11) Source(3, 7) + SourceIndex(0) --- >>> } 1 >^^^^^ 1 > >} -1 >Emitted(33, 6) Source(4, 2) + SourceIndex(0) +1 >Emitted(34, 6) Source(4, 2) + SourceIndex(0) --- >>>} >>>catch (e_1_1) { e_1 = { error: e_1_1 }; } diff --git a/tests/baselines/reference/ES5For-of37.js b/tests/baselines/reference/ES5For-of37.js index c9ea0236187..ada2710249f 100644 --- a/tests/baselines/reference/ES5For-of37.js +++ b/tests/baselines/reference/ES5For-of37.js @@ -17,15 +17,16 @@ for (const i of [0, 1, 2, 3, 4]) { //// [ES5For-of37.js] // https://github.com/microsoft/TypeScript/issues/30083 -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var e_1, _a, e_2, _b; try { diff --git a/tests/baselines/reference/blockScopedBindingsInDownlevelGenerator.js b/tests/baselines/reference/blockScopedBindingsInDownlevelGenerator.js index 9bb07d80b00..a0bc036f2a7 100644 --- a/tests/baselines/reference/blockScopedBindingsInDownlevelGenerator.js +++ b/tests/baselines/reference/blockScopedBindingsInDownlevelGenerator.js @@ -34,15 +34,16 @@ var __generator = (this && this.__generator) || function (thisArg, body) { if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; function a() { var _loop_1, _a, _b, i, e_1_1; diff --git a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js index 25b01aa5956..629cd3b0d9b 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.classMethods.es5.js @@ -282,15 +282,16 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var C4 = /** @class */ (function () { function C4() { @@ -363,15 +364,16 @@ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var C5 = /** @class */ (function () { function C5() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js index d4f6cd74132..622195d09df 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionDeclarations.es5.js @@ -236,15 +236,16 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; function f4() { return __asyncGenerator(this, arguments, function f4_1() { @@ -312,15 +313,16 @@ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; function f5() { return __asyncGenerator(this, arguments, function f5_1() { diff --git a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js index 55efe59aeba..7d8b9ad649b 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.functionExpressions.es5.js @@ -236,15 +236,16 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var f4 = function () { return __asyncGenerator(this, arguments, function () { @@ -312,15 +313,16 @@ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var f5 = function () { return __asyncGenerator(this, arguments, function () { diff --git a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js index 845d84e2c29..8677898f05d 100644 --- a/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js +++ b/tests/baselines/reference/emitter.asyncGenerators.objectLiteralMethods.es5.js @@ -256,15 +256,16 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var o4 = { f: function () { @@ -334,15 +335,16 @@ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; var o5 = { f: function () { diff --git a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.js b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.js index 80b2b04b8f0..e1a2a828b5c 100644 --- a/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.js +++ b/tests/baselines/reference/emptyVariableDeclarationBindingPatterns01_ES5iterable.js @@ -65,15 +65,16 @@ var __read = (this && this.__read) || function (o, n) { } return ar; }; -var __values = (this && this.__values) || function (o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; +var __values = (this && this.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); - return { + if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object not iterable." : "Symbol.iterator is not defined."); }; (function () { var a; From aa12ec440c9fcd1e74576c615cd3bf889fcc74db Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Thu, 25 Jul 2019 09:47:57 -0700 Subject: [PATCH 049/151] Fix smart select on last blank line of file (#32544) * Fix SmartSelection on last blank line of file * Add baseline --- src/services/smartSelection.ts | 7 +++++++ .../reference/smartSelection_lastBlankLine.baseline | 5 +++++ tests/cases/fourslash/smartSelection_lastBlankLine.ts | 5 +++++ 3 files changed, 17 insertions(+) create mode 100644 tests/baselines/reference/smartSelection_lastBlankLine.baseline create mode 100644 tests/cases/fourslash/smartSelection_lastBlankLine.ts diff --git a/src/services/smartSelection.ts b/src/services/smartSelection.ts index d0423ce031e..3765c39ed7a 100644 --- a/src/services/smartSelection.ts +++ b/src/services/smartSelection.ts @@ -64,6 +64,13 @@ namespace ts.SmartSelectionRange { parentNode = node; break; } + + // If we made it to the end of the for loop, we’re done. + // In practice, I’ve only seen this happen at the very end + // of a SourceFile. + if (i === children.length - 1) { + break outer; + } } } diff --git a/tests/baselines/reference/smartSelection_lastBlankLine.baseline b/tests/baselines/reference/smartSelection_lastBlankLine.baseline new file mode 100644 index 00000000000..3cbad44aac4 --- /dev/null +++ b/tests/baselines/reference/smartSelection_lastBlankLine.baseline @@ -0,0 +1,5 @@ +class C {} +/**/ + + +class C {}↲ diff --git a/tests/cases/fourslash/smartSelection_lastBlankLine.ts b/tests/cases/fourslash/smartSelection_lastBlankLine.ts new file mode 100644 index 00000000000..2f5cc3f07fc --- /dev/null +++ b/tests/cases/fourslash/smartSelection_lastBlankLine.ts @@ -0,0 +1,5 @@ +/// +////class C {} +/////**/ + +verify.baselineSmartSelection(); From dc415c5c5e81d6578f58cb1847d0c27926e8a005 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 25 Jul 2019 09:56:36 -0700 Subject: [PATCH 050/151] Infer between closely matching types in unions and intersections --- src/compiler/checker.ts | 116 +++++++++++++++++++--------------------- 1 file changed, 56 insertions(+), 60 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f56f56223cf..54c8d05e502 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15497,37 +15497,27 @@ namespace ts { } return; } - // Find each source constituent type that has an identically matching target constituent - // type, and for each such type infer from the type to itself. When inferring from a - // type to itself we effectively find all type parameter occurrences within that type - // and infer themselves as their type arguments. We have special handling for numeric - // and string literals because the number and string types are not represented as unions - // of all their possible values. - let matchingTypes: Type[] | undefined; - for (const t of (source).types) { - const matched = findMatchedType(t, target); - if (matched) { - (matchingTypes || (matchingTypes = [])).push(matched); - inferFromTypes(matched, matched); - } - } - // Next, to improve the quality of inferences, reduce the source and target types by - // removing the identically matched constituents. For example, when inferring from - // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. - if (matchingTypes) { - const s = removeTypesFromUnionOrIntersection(source, matchingTypes); - const t = removeTypesFromUnionOrIntersection(target, matchingTypes); - if (!(s && t)) return; - source = s; - target = t; - } - } - else if (target.flags & TypeFlags.Union && !(target.flags & TypeFlags.EnumLiteral) || target.flags & TypeFlags.Intersection) { - const matched = findMatchedType(source, target); - if (matched) { - inferFromTypes(matched, matched); + // First, infer between exactly matching source and target constituents and remove + // the matching types. Types exactly match when they are identical or, in union + // types, when the source is a literal and the target is the corresponding primitive. + const matching = target.flags & TypeFlags.Union ? isTypeOrBaseExactlyMatchedBy : isTypeExactlyMatchedBy; + const [tempSources, tempTargets] = inferFromMatchingTypes((source).types, (target).types, matching); + // Next, infer between closely matching source and target constituents and remove + // the matching types. Types closely match when they are instantiations of the same + // object type or instantiations of the same type alias. + const [sources, targets] = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy); + if (sources.length === 0 || targets.length === 0) { return; } + source = source.flags & TypeFlags.Union ? getUnionType(sources) : getIntersectionType(sources); + target = target.flags & TypeFlags.Union ? getUnionType(targets) : getIntersectionType(targets); + } + else if (target.flags & TypeFlags.Union && !(target.flags & TypeFlags.EnumLiteral) || target.flags & TypeFlags.Intersection) { + // This block of code is an optimized version of the block above for the simpler case + // of a singleton source type. + const matching = target.flags & TypeFlags.Union ? isTypeOrBaseExactlyMatchedBy : isTypeExactlyMatchedBy; + if (inferFromMatchingType(source, (target).types, matching)) return; + if (inferFromMatchingType(source, (target).types, isTypeCloselyMatchedBy)) return; } else if (target.flags & (TypeFlags.IndexedAccess | TypeFlags.Substitution)) { target = getActualTypeVariable(target); @@ -15675,6 +15665,35 @@ namespace ts { visited.set(key, inferenceCount - startCount); } + function inferFromMatchingType(source: Type, targets: Type[], matches: (s: Type, t: Type) => boolean) { + let matched = false; + for (const t of targets) { + if (matches(source, t)) { + inferFromTypes(source, t); + matched = true; + } + } + return matched; + } + + function inferFromMatchingTypes(sources: Type[], targets: Type[], matches: (s: Type, t: Type) => boolean): [Type[], Type[]] { + let matchedSources: Type[] | undefined; + let matchedTargets: Type[] | undefined; + for (const t of targets) { + for (const s of sources) { + if (matches(s, t)) { + inferFromTypes(s, t); + matchedSources = appendIfUnique(matchedSources, s); + matchedTargets = appendIfUnique(matchedTargets, t); + } + } + } + return [ + matchedSources ? filter(sources, t => !contains(matchedSources, t)) : sources, + matchedTargets ? filter(targets, t => !contains(matchedTargets, t)) : targets, + ]; + } + function inferFromTypeArguments(sourceTypes: readonly Type[], targetTypes: readonly Type[], variances: readonly VarianceFlags[]) { const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; for (let i = 0; i < count; i++) { @@ -15955,47 +15974,24 @@ namespace ts { } } - function isMatchableType(type: Type) { + function isNonObjectOrAnonymousType(type: Type) { // We exclude non-anonymous object types because some frameworks (e.g. Ember) rely on the ability to // infer between types that don't witness their type variables. Such types would otherwise be eliminated // because they appear identical. return !(type.flags & TypeFlags.Object) || !!(getObjectFlags(type) & ObjectFlags.Anonymous); } - function typeMatchedBySomeType(type: Type, types: Type[]): boolean { - for (const t of types) { - if (t === type || isMatchableType(t) && isMatchableType(type) && isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; + function isTypeExactlyMatchedBy(s: Type, t: Type) { + return s === t || isNonObjectOrAnonymousType(s) && isNonObjectOrAnonymousType(t) && isTypeIdenticalTo(s, t); } - function findMatchedType(type: Type, target: UnionOrIntersectionType) { - if (typeMatchedBySomeType(type, target.types)) { - return type; - } - if (type.flags & (TypeFlags.NumberLiteral | TypeFlags.StringLiteral) && target.flags & TypeFlags.Union) { - const base = getBaseTypeOfLiteralType(type); - if (typeMatchedBySomeType(base, target.types)) { - return base; - } - } - return undefined; + function isTypeOrBaseExactlyMatchedBy(s: Type, t: Type) { + return isTypeExactlyMatchedBy(s, t) || !!(s.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) && isTypeIdenticalTo(getBaseTypeOfLiteralType(s), t); } - /** - * Return a new union or intersection type computed by removing a given set of types - * from a given union or intersection type. - */ - function removeTypesFromUnionOrIntersection(type: UnionOrIntersectionType, typesToRemove: Type[]) { - const reducedTypes: Type[] = []; - for (const t of type.types) { - if (!typeMatchedBySomeType(t, typesToRemove)) { - reducedTypes.push(t); - } - } - return reducedTypes.length ? type.flags & TypeFlags.Union ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes) : undefined; + function isTypeCloselyMatchedBy(s: Type, t: Type) { + return !!(s.flags & TypeFlags.Object && t.flags & TypeFlags.Object && s.symbol && s.symbol === t.symbol || + s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol); } function hasPrimitiveConstraint(type: TypeParameter): boolean { From 772bee5e84f80a7e76c623b1c39d1eb80d8e9b4a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 25 Jul 2019 10:23:03 -0700 Subject: [PATCH 051/151] Property assignment uses parent type annotation (#32553) * Property assignment uses parent type annotation First draft, will write full explanation later. Also makes sure that jsdoc is ignored in TS. It was not before. * Update baselines --- src/compiler/checker.ts | 25 +++++++---- .../expandoFunctionContextualTypes.types | 2 +- .../expandoFunctionContextualTypesJs.types | 2 +- .../propertyAssignmentUseParentType1.js | 26 +++++++++++ .../propertyAssignmentUseParentType1.symbols | 35 +++++++++++++++ .../propertyAssignmentUseParentType1.types | 44 +++++++++++++++++++ ...ropertyAssignmentUseParentType2.errors.txt | 24 ++++++++++ .../propertyAssignmentUseParentType2.symbols | 30 +++++++++++++ .../propertyAssignmentUseParentType2.types | 42 ++++++++++++++++++ .../salsa/propertyAssignmentUseParentType1.ts | 13 ++++++ .../salsa/propertyAssignmentUseParentType2.ts | 18 ++++++++ 11 files changed, 250 insertions(+), 11 deletions(-) create mode 100644 tests/baselines/reference/propertyAssignmentUseParentType1.js create mode 100644 tests/baselines/reference/propertyAssignmentUseParentType1.symbols create mode 100644 tests/baselines/reference/propertyAssignmentUseParentType1.types create mode 100644 tests/baselines/reference/propertyAssignmentUseParentType2.errors.txt create mode 100644 tests/baselines/reference/propertyAssignmentUseParentType2.symbols create mode 100644 tests/baselines/reference/propertyAssignmentUseParentType2.types create mode 100644 tests/cases/conformance/salsa/propertyAssignmentUseParentType1.ts create mode 100644 tests/cases/conformance/salsa/propertyAssignmentUseParentType2.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f56f56223cf..2f466267f9d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5396,7 +5396,7 @@ namespace ts { return undefined; } - function getWidenedTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol?: Symbol) { + function getWidenedTypeForAssignmentDeclaration(symbol: Symbol, resolvedSymbol?: Symbol) { // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers const container = getAssignedExpandoInitializer(symbol.valueDeclaration); if (container) { @@ -5429,7 +5429,7 @@ namespace ts { } } if (!isCallExpression(expression)) { - jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); } if (!jsdocType) { (types || (types = [])).push((isBinaryExpression(expression) || isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); @@ -5478,8 +5478,8 @@ namespace ts { return type; } - function getJSDocTypeFromAssignmentDeclaration(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { - const typeNode = getJSDocType(expression.parent); + function getAnnotatedTypeForAssignmentDeclaration(declaredType: Type | undefined, expression: Expression, symbol: Symbol, declaration: Declaration) { + const typeNode = getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { const type = getWidenedType(getTypeFromTypeNode(typeNode)); if (!declaredType) { @@ -5489,6 +5489,13 @@ namespace ts { errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } + if (symbol.parent) { + const typeNode = getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); + if (typeNode) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode), symbol.escapedName); + } + } + return declaredType; } @@ -5783,7 +5790,7 @@ namespace ts { } else if (isInJSFile(declaration) && (isCallExpression(declaration) || isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromAssignmentDeclaration(symbol); + type = getWidenedTypeForAssignmentDeclaration(symbol); } else if (isJSDocPropertyLikeTag(declaration) || isPropertyAccessExpression(declaration) @@ -5798,7 +5805,7 @@ namespace ts { return getTypeOfFuncClassEnumModule(symbol); } type = isBinaryExpression(declaration.parent) ? - getWidenedTypeFromAssignmentDeclaration(symbol) : + getWidenedTypeForAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (isPropertyAssignment(declaration)) { @@ -5969,7 +5976,7 @@ namespace ts { } else if (declaration.kind === SyntaxKind.BinaryExpression || declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) { - return getWidenedTypeFromAssignmentDeclaration(symbol); + return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { const resolvedModule = resolveExternalModuleSymbol(symbol); @@ -5978,7 +5985,7 @@ namespace ts { return errorType; } const exportEquals = getMergedSymbol(symbol.exports!.get(InternalSymbolName.ExportEquals)!); - const type = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + const type = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } @@ -19157,7 +19164,7 @@ namespace ts { } /** - * Woah! Do you really want to use this function? + * Whoa! Do you really want to use this function? * * Unless you're trying to get the *non-apparent* type for a * value-literal type or you're authoring relevant portions of this algorithm, diff --git a/tests/baselines/reference/expandoFunctionContextualTypes.types b/tests/baselines/reference/expandoFunctionContextualTypes.types index e1eca92659c..915b168776f 100644 --- a/tests/baselines/reference/expandoFunctionContextualTypes.types +++ b/tests/baselines/reference/expandoFunctionContextualTypes.types @@ -12,7 +12,7 @@ interface StatelessComponent

{ const MyComponent: StatelessComponent = () => null as any; >MyComponent : StatelessComponent ->() => null as any : { (): any; defaultProps: { color: "red"; }; } +>() => null as any : { (): any; defaultProps: Partial; } >null as any : any >null : null diff --git a/tests/baselines/reference/expandoFunctionContextualTypesJs.types b/tests/baselines/reference/expandoFunctionContextualTypesJs.types index 081c57c0dac..82442a9db4a 100644 --- a/tests/baselines/reference/expandoFunctionContextualTypesJs.types +++ b/tests/baselines/reference/expandoFunctionContextualTypesJs.types @@ -10,7 +10,7 @@ */ const MyComponent = () => /* @type {any} */(null); >MyComponent : { (): any; defaultProps?: Partial<{ color: "red" | "blue"; }>; } ->() => /* @type {any} */(null) : { (): any; defaultProps: { color: "red"; }; } +>() => /* @type {any} */(null) : { (): any; defaultProps: Partial<{ color: "red" | "blue"; }>; } >(null) : null >null : null diff --git a/tests/baselines/reference/propertyAssignmentUseParentType1.js b/tests/baselines/reference/propertyAssignmentUseParentType1.js new file mode 100644 index 00000000000..5e839a31da4 --- /dev/null +++ b/tests/baselines/reference/propertyAssignmentUseParentType1.js @@ -0,0 +1,26 @@ +//// [propertyAssignmentUseParentType1.ts] +interface N { + (): boolean + num: 123; +} +export const interfaced: N = () => true; +interfaced.num = 123; + +export const inlined: { (): boolean; nun: 456 } = () => true; +inlined.nun = 456; + +export const ignoreJsdoc = () => true; +/** @type {string} make sure to ignore jsdoc! */ +ignoreJsdoc.extra = 111 + + +//// [propertyAssignmentUseParentType1.js] +"use strict"; +exports.__esModule = true; +exports.interfaced = function () { return true; }; +exports.interfaced.num = 123; +exports.inlined = function () { return true; }; +exports.inlined.nun = 456; +exports.ignoreJsdoc = function () { return true; }; +/** @type {string} make sure to ignore jsdoc! */ +exports.ignoreJsdoc.extra = 111; diff --git a/tests/baselines/reference/propertyAssignmentUseParentType1.symbols b/tests/baselines/reference/propertyAssignmentUseParentType1.symbols new file mode 100644 index 00000000000..081e2f12604 --- /dev/null +++ b/tests/baselines/reference/propertyAssignmentUseParentType1.symbols @@ -0,0 +1,35 @@ +=== tests/cases/conformance/salsa/propertyAssignmentUseParentType1.ts === +interface N { +>N : Symbol(N, Decl(propertyAssignmentUseParentType1.ts, 0, 0)) + + (): boolean + num: 123; +>num : Symbol(N.num, Decl(propertyAssignmentUseParentType1.ts, 1, 15)) +} +export const interfaced: N = () => true; +>interfaced : Symbol(interfaced, Decl(propertyAssignmentUseParentType1.ts, 4, 12), Decl(propertyAssignmentUseParentType1.ts, 4, 40)) +>N : Symbol(N, Decl(propertyAssignmentUseParentType1.ts, 0, 0)) + +interfaced.num = 123; +>interfaced.num : Symbol(N.num, Decl(propertyAssignmentUseParentType1.ts, 1, 15)) +>interfaced : Symbol(interfaced, Decl(propertyAssignmentUseParentType1.ts, 4, 12), Decl(propertyAssignmentUseParentType1.ts, 4, 40)) +>num : Symbol(N.num, Decl(propertyAssignmentUseParentType1.ts, 1, 15)) + +export const inlined: { (): boolean; nun: 456 } = () => true; +>inlined : Symbol(inlined, Decl(propertyAssignmentUseParentType1.ts, 7, 12), Decl(propertyAssignmentUseParentType1.ts, 7, 61)) +>nun : Symbol(nun, Decl(propertyAssignmentUseParentType1.ts, 7, 36)) + +inlined.nun = 456; +>inlined.nun : Symbol(nun, Decl(propertyAssignmentUseParentType1.ts, 7, 36)) +>inlined : Symbol(inlined, Decl(propertyAssignmentUseParentType1.ts, 7, 12), Decl(propertyAssignmentUseParentType1.ts, 7, 61)) +>nun : Symbol(nun, Decl(propertyAssignmentUseParentType1.ts, 7, 36)) + +export const ignoreJsdoc = () => true; +>ignoreJsdoc : Symbol(ignoreJsdoc, Decl(propertyAssignmentUseParentType1.ts, 10, 12), Decl(propertyAssignmentUseParentType1.ts, 10, 38)) + +/** @type {string} make sure to ignore jsdoc! */ +ignoreJsdoc.extra = 111 +>ignoreJsdoc.extra : Symbol(ignoreJsdoc.extra, Decl(propertyAssignmentUseParentType1.ts, 10, 38)) +>ignoreJsdoc : Symbol(ignoreJsdoc, Decl(propertyAssignmentUseParentType1.ts, 10, 12), Decl(propertyAssignmentUseParentType1.ts, 10, 38)) +>extra : Symbol(ignoreJsdoc.extra, Decl(propertyAssignmentUseParentType1.ts, 10, 38)) + diff --git a/tests/baselines/reference/propertyAssignmentUseParentType1.types b/tests/baselines/reference/propertyAssignmentUseParentType1.types new file mode 100644 index 00000000000..f3bd5010b20 --- /dev/null +++ b/tests/baselines/reference/propertyAssignmentUseParentType1.types @@ -0,0 +1,44 @@ +=== tests/cases/conformance/salsa/propertyAssignmentUseParentType1.ts === +interface N { + (): boolean + num: 123; +>num : 123 +} +export const interfaced: N = () => true; +>interfaced : N +>() => true : { (): true; num: 123; } +>true : true + +interfaced.num = 123; +>interfaced.num = 123 : 123 +>interfaced.num : 123 +>interfaced : N +>num : 123 +>123 : 123 + +export const inlined: { (): boolean; nun: 456 } = () => true; +>inlined : { (): boolean; nun: 456; } +>nun : 456 +>() => true : { (): true; nun: 456; } +>true : true + +inlined.nun = 456; +>inlined.nun = 456 : 456 +>inlined.nun : 456 +>inlined : { (): boolean; nun: 456; } +>nun : 456 +>456 : 456 + +export const ignoreJsdoc = () => true; +>ignoreJsdoc : { (): boolean; extra: number; } +>() => true : { (): boolean; extra: number; } +>true : true + +/** @type {string} make sure to ignore jsdoc! */ +ignoreJsdoc.extra = 111 +>ignoreJsdoc.extra = 111 : 111 +>ignoreJsdoc.extra : number +>ignoreJsdoc : { (): boolean; extra: number; } +>extra : number +>111 : 111 + diff --git a/tests/baselines/reference/propertyAssignmentUseParentType2.errors.txt b/tests/baselines/reference/propertyAssignmentUseParentType2.errors.txt new file mode 100644 index 00000000000..b88e276b405 --- /dev/null +++ b/tests/baselines/reference/propertyAssignmentUseParentType2.errors.txt @@ -0,0 +1,24 @@ +tests/cases/conformance/salsa/propertyAssignmentUseParentType2.js(11,14): error TS2322: Type '{ (): boolean; nuo: 1000; }' is not assignable to type '{ (): boolean; nuo: 789; }'. + Types of property 'nuo' are incompatible. + Type '1000' is not assignable to type '789'. + + +==== tests/cases/conformance/salsa/propertyAssignmentUseParentType2.js (1 errors) ==== + /** @type {{ (): boolean; nuo: 789 }} */ + export const inlined = () => true + inlined.nuo = 789 + + /** @type {{ (): boolean; nuo: 789 }} */ + export const duplicated = () => true + /** @type {789} */ + duplicated.nuo = 789 + + /** @type {{ (): boolean; nuo: 789 }} */ + export const conflictingDuplicated = () => true + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ (): boolean; nuo: 1000; }' is not assignable to type '{ (): boolean; nuo: 789; }'. +!!! error TS2322: Types of property 'nuo' are incompatible. +!!! error TS2322: Type '1000' is not assignable to type '789'. + /** @type {1000} */ + conflictingDuplicated.nuo = 789 + \ No newline at end of file diff --git a/tests/baselines/reference/propertyAssignmentUseParentType2.symbols b/tests/baselines/reference/propertyAssignmentUseParentType2.symbols new file mode 100644 index 00000000000..93b8b9290da --- /dev/null +++ b/tests/baselines/reference/propertyAssignmentUseParentType2.symbols @@ -0,0 +1,30 @@ +=== tests/cases/conformance/salsa/propertyAssignmentUseParentType2.js === +/** @type {{ (): boolean; nuo: 789 }} */ +export const inlined = () => true +>inlined : Symbol(inlined, Decl(propertyAssignmentUseParentType2.js, 1, 12), Decl(propertyAssignmentUseParentType2.js, 1, 33)) + +inlined.nuo = 789 +>inlined.nuo : Symbol(nuo, Decl(propertyAssignmentUseParentType2.js, 0, 25)) +>inlined : Symbol(inlined, Decl(propertyAssignmentUseParentType2.js, 1, 12), Decl(propertyAssignmentUseParentType2.js, 1, 33)) +>nuo : Symbol(nuo, Decl(propertyAssignmentUseParentType2.js, 0, 25)) + +/** @type {{ (): boolean; nuo: 789 }} */ +export const duplicated = () => true +>duplicated : Symbol(duplicated, Decl(propertyAssignmentUseParentType2.js, 5, 12), Decl(propertyAssignmentUseParentType2.js, 5, 36)) + +/** @type {789} */ +duplicated.nuo = 789 +>duplicated.nuo : Symbol(nuo, Decl(propertyAssignmentUseParentType2.js, 4, 25)) +>duplicated : Symbol(duplicated, Decl(propertyAssignmentUseParentType2.js, 5, 12), Decl(propertyAssignmentUseParentType2.js, 5, 36)) +>nuo : Symbol(nuo, Decl(propertyAssignmentUseParentType2.js, 4, 25)) + +/** @type {{ (): boolean; nuo: 789 }} */ +export const conflictingDuplicated = () => true +>conflictingDuplicated : Symbol(conflictingDuplicated, Decl(propertyAssignmentUseParentType2.js, 10, 12), Decl(propertyAssignmentUseParentType2.js, 10, 47)) + +/** @type {1000} */ +conflictingDuplicated.nuo = 789 +>conflictingDuplicated.nuo : Symbol(nuo, Decl(propertyAssignmentUseParentType2.js, 9, 25)) +>conflictingDuplicated : Symbol(conflictingDuplicated, Decl(propertyAssignmentUseParentType2.js, 10, 12), Decl(propertyAssignmentUseParentType2.js, 10, 47)) +>nuo : Symbol(nuo, Decl(propertyAssignmentUseParentType2.js, 9, 25)) + diff --git a/tests/baselines/reference/propertyAssignmentUseParentType2.types b/tests/baselines/reference/propertyAssignmentUseParentType2.types new file mode 100644 index 00000000000..24118a9ee73 --- /dev/null +++ b/tests/baselines/reference/propertyAssignmentUseParentType2.types @@ -0,0 +1,42 @@ +=== tests/cases/conformance/salsa/propertyAssignmentUseParentType2.js === +/** @type {{ (): boolean; nuo: 789 }} */ +export const inlined = () => true +>inlined : { (): boolean; nuo: 789; } +>() => true : { (): boolean; nuo: 789; } +>true : true + +inlined.nuo = 789 +>inlined.nuo = 789 : 789 +>inlined.nuo : 789 +>inlined : { (): boolean; nuo: 789; } +>nuo : 789 +>789 : 789 + +/** @type {{ (): boolean; nuo: 789 }} */ +export const duplicated = () => true +>duplicated : { (): boolean; nuo: 789; } +>() => true : { (): boolean; nuo: 789; } +>true : true + +/** @type {789} */ +duplicated.nuo = 789 +>duplicated.nuo = 789 : 789 +>duplicated.nuo : 789 +>duplicated : { (): boolean; nuo: 789; } +>nuo : 789 +>789 : 789 + +/** @type {{ (): boolean; nuo: 789 }} */ +export const conflictingDuplicated = () => true +>conflictingDuplicated : { (): boolean; nuo: 789; } +>() => true : { (): boolean; nuo: 1000; } +>true : true + +/** @type {1000} */ +conflictingDuplicated.nuo = 789 +>conflictingDuplicated.nuo = 789 : 789 +>conflictingDuplicated.nuo : 789 +>conflictingDuplicated : { (): boolean; nuo: 789; } +>nuo : 789 +>789 : 789 + diff --git a/tests/cases/conformance/salsa/propertyAssignmentUseParentType1.ts b/tests/cases/conformance/salsa/propertyAssignmentUseParentType1.ts new file mode 100644 index 00000000000..500ae6f2fe3 --- /dev/null +++ b/tests/cases/conformance/salsa/propertyAssignmentUseParentType1.ts @@ -0,0 +1,13 @@ +interface N { + (): boolean + num: 123; +} +export const interfaced: N = () => true; +interfaced.num = 123; + +export const inlined: { (): boolean; nun: 456 } = () => true; +inlined.nun = 456; + +export const ignoreJsdoc = () => true; +/** @type {string} make sure to ignore jsdoc! */ +ignoreJsdoc.extra = 111 diff --git a/tests/cases/conformance/salsa/propertyAssignmentUseParentType2.ts b/tests/cases/conformance/salsa/propertyAssignmentUseParentType2.ts new file mode 100644 index 00000000000..53696abbf81 --- /dev/null +++ b/tests/cases/conformance/salsa/propertyAssignmentUseParentType2.ts @@ -0,0 +1,18 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @Filename: propertyAssignmentUseParentType2.js + +/** @type {{ (): boolean; nuo: 789 }} */ +export const inlined = () => true +inlined.nuo = 789 + +/** @type {{ (): boolean; nuo: 789 }} */ +export const duplicated = () => true +/** @type {789} */ +duplicated.nuo = 789 + +/** @type {{ (): boolean; nuo: 789 }} */ +export const conflictingDuplicated = () => true +/** @type {1000} */ +conflictingDuplicated.nuo = 789 From 35de142943ea867f302fc8318afa9e9f9bb7c0ad Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 25 Jul 2019 11:50:50 -0700 Subject: [PATCH 052/151] Accept new baselines --- ...nalNoInfiniteInstantiationDepth.errors.txt | 26 +++++++------------ ...ferredInferenceAllowsAssignment.errors.txt | 26 +++++++------------ 2 files changed, 20 insertions(+), 32 deletions(-) diff --git a/tests/baselines/reference/circularlyConstrainedMappedTypeContainingConditionalNoInfiniteInstantiationDepth.errors.txt b/tests/baselines/reference/circularlyConstrainedMappedTypeContainingConditionalNoInfiniteInstantiationDepth.errors.txt index c7a323f1283..4fad6997145 100644 --- a/tests/baselines/reference/circularlyConstrainedMappedTypeContainingConditionalNoInfiniteInstantiationDepth.errors.txt +++ b/tests/baselines/reference/circularlyConstrainedMappedTypeContainingConditionalNoInfiniteInstantiationDepth.errors.txt @@ -45,14 +45,11 @@ tests/cases/compiler/circularlyConstrainedMappedTypeContainingConditionalNoInfin Type 'TInjectedProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. Type 'TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. - Type 'GetProps[string] | (TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string])' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. - Type 'GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. - Type 'GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. ==== tests/cases/compiler/circularlyConstrainedMappedTypeContainingConditionalNoInfiniteInstantiationDepth.ts (1 errors) ==== @@ -167,12 +164,9 @@ tests/cases/compiler/circularlyConstrainedMappedTypeContainingConditionalNoInfin !!! error TS2344: Type 'TInjectedProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. !!! error TS2344: Type 'TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. !!! error TS2344: Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. -!!! error TS2344: Type 'GetProps[string] | (TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string])' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. -!!! error TS2344: Type 'GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. -!!! error TS2344: Type 'GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. \ No newline at end of file diff --git a/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.errors.txt b/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.errors.txt index 0556ae25c91..0acfd4a8365 100644 --- a/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.errors.txt +++ b/tests/baselines/reference/reactReduxLikeDeferredInferenceAllowsAssignment.errors.txt @@ -45,14 +45,11 @@ tests/cases/compiler/reactReduxLikeDeferredInferenceAllowsAssignment.ts(76,50): Type 'TInjectedProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. Type 'TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. - Type 'GetProps[string] | (TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string])' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. - Type 'GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. - Type 'GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. - Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. + Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. ==== tests/cases/compiler/reactReduxLikeDeferredInferenceAllowsAssignment.ts (1 errors) ==== @@ -180,14 +177,11 @@ tests/cases/compiler/reactReduxLikeDeferredInferenceAllowsAssignment.ts(76,50): !!! error TS2344: Type 'TInjectedProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. !!! error TS2344: Type 'TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. !!! error TS2344: Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. -!!! error TS2344: Type 'GetProps[string] | (TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string])' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. -!!! error TS2344: Type 'GetProps[string]' is not assignable to type '(TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never) | undefined'. -!!! error TS2344: Type 'GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. -!!! error TS2344: Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & string] extends GetProps[keyof TInjectedProps & string] ? GetProps[keyof TInjectedProps & string] : TInjectedProps[keyof TInjectedProps & string] : GetProps[string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'keyof GetProps & string extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & keyof GetProps & string] extends GetProps[keyof TInjectedProps & keyof GetProps & string] ? GetProps[keyof TInjectedProps & keyof GetProps & string] : TInjectedProps[keyof TInjectedProps & keyof GetProps & string] : GetProps[keyof GetProps & string]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[keyof TInjectedProps & Extract>] extends GetProps[keyof TInjectedProps & Extract>] ? GetProps[keyof TInjectedProps & Extract>] : TInjectedProps[keyof TInjectedProps & Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'Extract> extends keyof TInjectedProps ? TInjectedProps[Extract>] extends GetProps[Extract>] ? GetProps[Extract>] : TInjectedProps[Extract>] : GetProps[Extract>]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. +!!! error TS2344: Type 'P extends keyof TInjectedProps ? TInjectedProps[P] extends GetProps[P] ? GetProps[P] : TInjectedProps[P] : GetProps[P]' is not assignable to type 'TInjectedProps[P] extends GetProps[P] ? GetProps[P] : never'. >; declare const connect: { From b9d27c0f2ce5df82b8899aca94ed752b626978b0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 25 Jul 2019 11:52:08 -0700 Subject: [PATCH 053/151] Add regression tests --- .../unionAndIntersectionInference3.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts index aad083a626b..17057de2b84 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts @@ -1,7 +1,42 @@ // @strict: true +// @target: esnext // Repro from #30720 type Maybe = T | undefined; declare function concatMaybe(...args: (Maybe | Maybe[])[]): T[]; concatMaybe([1, 2, 3], 4); + +// Repros from #32247 + +const g: (com: () => Iterator | AsyncIterator) => Promise = async (com: () => Iterator | AsyncIterator): Promise => { + throw com; +}; + +interface Foo1 { + test(value: T): void; +} + +interface Bar1 { + test(value: T | PromiseLike): void; +} + +declare let f1: (x: Foo1 | Bar1) => Promise; +declare let f2: (x: Foo1 | Bar1) => Promise; + +f1 = f2; +f2 = f1; + +type Foo2 = { + test(value: T): void; +} + +type Bar2 = { + test(value: T | PromiseLike): void; +} + +declare let g1: (x: Foo2 | Bar2) => Promise; +declare let g2: (x: Foo2 | Bar2) => Promise; + +g1 = g2; +g2 = g1; From 540134840da0acea39f103b12719392c41b9a67d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 25 Jul 2019 11:52:15 -0700 Subject: [PATCH 054/151] Accept new baselines --- .../unionAndIntersectionInference3.js | 42 ++++++ .../unionAndIntersectionInference3.symbols | 142 ++++++++++++++++++ .../unionAndIntersectionInference3.types | 77 ++++++++++ 3 files changed, 261 insertions(+) diff --git a/tests/baselines/reference/unionAndIntersectionInference3.js b/tests/baselines/reference/unionAndIntersectionInference3.js index 4cc0c2f667e..c9f5cffa1f7 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.js +++ b/tests/baselines/reference/unionAndIntersectionInference3.js @@ -4,9 +4,51 @@ type Maybe = T | undefined; declare function concatMaybe(...args: (Maybe | Maybe[])[]): T[]; concatMaybe([1, 2, 3], 4); + +// Repros from #32247 + +const g: (com: () => Iterator | AsyncIterator) => Promise = async (com: () => Iterator | AsyncIterator): Promise => { + throw com; +}; + +interface Foo1 { + test(value: T): void; +} + +interface Bar1 { + test(value: T | PromiseLike): void; +} + +declare let f1: (x: Foo1 | Bar1) => Promise; +declare let f2: (x: Foo1 | Bar1) => Promise; + +f1 = f2; +f2 = f1; + +type Foo2 = { + test(value: T): void; +} + +type Bar2 = { + test(value: T | PromiseLike): void; +} + +declare let g1: (x: Foo2 | Bar2) => Promise; +declare let g2: (x: Foo2 | Bar2) => Promise; + +g1 = g2; +g2 = g1; //// [unionAndIntersectionInference3.js] "use strict"; // Repro from #30720 concatMaybe([1, 2, 3], 4); +// Repros from #32247 +const g = async (com) => { + throw com; +}; +f1 = f2; +f2 = f1; +g1 = g2; +g2 = g1; diff --git a/tests/baselines/reference/unionAndIntersectionInference3.symbols b/tests/baselines/reference/unionAndIntersectionInference3.symbols index be24bc0cc77..b854ee1ce42 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.symbols +++ b/tests/baselines/reference/unionAndIntersectionInference3.symbols @@ -19,3 +19,145 @@ declare function concatMaybe(...args: (Maybe | Maybe[])[]): T[]; concatMaybe([1, 2, 3], 4); >concatMaybe : Symbol(concatMaybe, Decl(unionAndIntersectionInference3.ts, 2, 30)) +// Repros from #32247 + +const g: (com: () => Iterator | AsyncIterator) => Promise = async (com: () => Iterator | AsyncIterator): Promise => { +>g : Symbol(g, Decl(unionAndIntersectionInference3.ts, 8, 5)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 10)) +>R : Symbol(R, Decl(unionAndIntersectionInference3.ts, 8, 12)) +>S : Symbol(S, Decl(unionAndIntersectionInference3.ts, 8, 15)) +>com : Symbol(com, Decl(unionAndIntersectionInference3.ts, 8, 19)) +>Iterator : Symbol(Iterator, Decl(lib.es2015.iterable.d.ts, --, --)) +>S : Symbol(S, Decl(unionAndIntersectionInference3.ts, 8, 15)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 10)) +>R : Symbol(R, Decl(unionAndIntersectionInference3.ts, 8, 12)) +>AsyncIterator : Symbol(AsyncIterator, Decl(lib.es2018.asynciterable.d.ts, --, --)) +>S : Symbol(S, Decl(unionAndIntersectionInference3.ts, 8, 15)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 10)) +>R : Symbol(R, Decl(unionAndIntersectionInference3.ts, 8, 12)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 10)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 97)) +>R : Symbol(R, Decl(unionAndIntersectionInference3.ts, 8, 99)) +>S : Symbol(S, Decl(unionAndIntersectionInference3.ts, 8, 102)) +>com : Symbol(com, Decl(unionAndIntersectionInference3.ts, 8, 106)) +>Iterator : Symbol(Iterator, Decl(lib.es2015.iterable.d.ts, --, --)) +>S : Symbol(S, Decl(unionAndIntersectionInference3.ts, 8, 102)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 97)) +>R : Symbol(R, Decl(unionAndIntersectionInference3.ts, 8, 99)) +>AsyncIterator : Symbol(AsyncIterator, Decl(lib.es2018.asynciterable.d.ts, --, --)) +>S : Symbol(S, Decl(unionAndIntersectionInference3.ts, 8, 102)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 97)) +>R : Symbol(R, Decl(unionAndIntersectionInference3.ts, 8, 99)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 8, 97)) + + throw com; +>com : Symbol(com, Decl(unionAndIntersectionInference3.ts, 8, 106)) + +}; + +interface Foo1 { +>Foo1 : Symbol(Foo1, Decl(unionAndIntersectionInference3.ts, 10, 2)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 12, 15)) + + test(value: T): void; +>test : Symbol(Foo1.test, Decl(unionAndIntersectionInference3.ts, 12, 19)) +>value : Symbol(value, Decl(unionAndIntersectionInference3.ts, 13, 9)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 12, 15)) +} + +interface Bar1 { +>Bar1 : Symbol(Bar1, Decl(unionAndIntersectionInference3.ts, 14, 1)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 16, 15)) + + test(value: T | PromiseLike): void; +>test : Symbol(Bar1.test, Decl(unionAndIntersectionInference3.ts, 16, 19)) +>value : Symbol(value, Decl(unionAndIntersectionInference3.ts, 17, 9)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 16, 15)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 16, 15)) +} + +declare let f1: (x: Foo1 | Bar1) => Promise; +>f1 : Symbol(f1, Decl(unionAndIntersectionInference3.ts, 20, 11)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 20, 17)) +>x : Symbol(x, Decl(unionAndIntersectionInference3.ts, 20, 20)) +>Foo1 : Symbol(Foo1, Decl(unionAndIntersectionInference3.ts, 10, 2)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 20, 17)) +>Bar1 : Symbol(Bar1, Decl(unionAndIntersectionInference3.ts, 14, 1)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 20, 17)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 20, 17)) + +declare let f2: (x: Foo1 | Bar1) => Promise; +>f2 : Symbol(f2, Decl(unionAndIntersectionInference3.ts, 21, 11)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 21, 17)) +>x : Symbol(x, Decl(unionAndIntersectionInference3.ts, 21, 20)) +>Foo1 : Symbol(Foo1, Decl(unionAndIntersectionInference3.ts, 10, 2)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 21, 17)) +>Bar1 : Symbol(Bar1, Decl(unionAndIntersectionInference3.ts, 14, 1)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 21, 17)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 21, 17)) + +f1 = f2; +>f1 : Symbol(f1, Decl(unionAndIntersectionInference3.ts, 20, 11)) +>f2 : Symbol(f2, Decl(unionAndIntersectionInference3.ts, 21, 11)) + +f2 = f1; +>f2 : Symbol(f2, Decl(unionAndIntersectionInference3.ts, 21, 11)) +>f1 : Symbol(f1, Decl(unionAndIntersectionInference3.ts, 20, 11)) + +type Foo2 = { +>Foo2 : Symbol(Foo2, Decl(unionAndIntersectionInference3.ts, 24, 8)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 26, 10)) + + test(value: T): void; +>test : Symbol(test, Decl(unionAndIntersectionInference3.ts, 26, 16)) +>value : Symbol(value, Decl(unionAndIntersectionInference3.ts, 27, 9)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 26, 10)) +} + +type Bar2 = { +>Bar2 : Symbol(Bar2, Decl(unionAndIntersectionInference3.ts, 28, 1)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 30, 10)) + + test(value: T | PromiseLike): void; +>test : Symbol(test, Decl(unionAndIntersectionInference3.ts, 30, 16)) +>value : Symbol(value, Decl(unionAndIntersectionInference3.ts, 31, 9)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 30, 10)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 30, 10)) +} + +declare let g1: (x: Foo2 | Bar2) => Promise; +>g1 : Symbol(g1, Decl(unionAndIntersectionInference3.ts, 34, 11)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 34, 17)) +>x : Symbol(x, Decl(unionAndIntersectionInference3.ts, 34, 20)) +>Foo2 : Symbol(Foo2, Decl(unionAndIntersectionInference3.ts, 24, 8)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 34, 17)) +>Bar2 : Symbol(Bar2, Decl(unionAndIntersectionInference3.ts, 28, 1)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 34, 17)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 34, 17)) + +declare let g2: (x: Foo2 | Bar2) => Promise; +>g2 : Symbol(g2, Decl(unionAndIntersectionInference3.ts, 35, 11)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 35, 17)) +>x : Symbol(x, Decl(unionAndIntersectionInference3.ts, 35, 20)) +>Foo2 : Symbol(Foo2, Decl(unionAndIntersectionInference3.ts, 24, 8)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 35, 17)) +>Bar2 : Symbol(Bar2, Decl(unionAndIntersectionInference3.ts, 28, 1)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 35, 17)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 35, 17)) + +g1 = g2; +>g1 : Symbol(g1, Decl(unionAndIntersectionInference3.ts, 34, 11)) +>g2 : Symbol(g2, Decl(unionAndIntersectionInference3.ts, 35, 11)) + +g2 = g1; +>g2 : Symbol(g2, Decl(unionAndIntersectionInference3.ts, 35, 11)) +>g1 : Symbol(g1, Decl(unionAndIntersectionInference3.ts, 34, 11)) + diff --git a/tests/baselines/reference/unionAndIntersectionInference3.types b/tests/baselines/reference/unionAndIntersectionInference3.types index 8497cb1e516..acbca0a1eae 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.types +++ b/tests/baselines/reference/unionAndIntersectionInference3.types @@ -17,3 +17,80 @@ concatMaybe([1, 2, 3], 4); >3 : 3 >4 : 4 +// Repros from #32247 + +const g: (com: () => Iterator | AsyncIterator) => Promise = async (com: () => Iterator | AsyncIterator): Promise => { +>g : (com: () => Iterator | AsyncIterator) => Promise +>com : () => Iterator | AsyncIterator +>async (com: () => Iterator | AsyncIterator): Promise => { throw com;} : (com: () => Iterator | AsyncIterator) => Promise +>com : () => Iterator | AsyncIterator + + throw com; +>com : () => Iterator | AsyncIterator + +}; + +interface Foo1 { + test(value: T): void; +>test : (value: T) => void +>value : T +} + +interface Bar1 { + test(value: T | PromiseLike): void; +>test : (value: T | PromiseLike) => void +>value : T | PromiseLike +} + +declare let f1: (x: Foo1 | Bar1) => Promise; +>f1 : (x: Foo1 | Bar1) => Promise +>x : Foo1 | Bar1 + +declare let f2: (x: Foo1 | Bar1) => Promise; +>f2 : (x: Foo1 | Bar1) => Promise +>x : Foo1 | Bar1 + +f1 = f2; +>f1 = f2 : (x: Foo1 | Bar1) => Promise +>f1 : (x: Foo1 | Bar1) => Promise +>f2 : (x: Foo1 | Bar1) => Promise + +f2 = f1; +>f2 = f1 : (x: Foo1 | Bar1) => Promise +>f2 : (x: Foo1 | Bar1) => Promise +>f1 : (x: Foo1 | Bar1) => Promise + +type Foo2 = { +>Foo2 : Foo2 + + test(value: T): void; +>test : (value: T) => void +>value : T +} + +type Bar2 = { +>Bar2 : Bar2 + + test(value: T | PromiseLike): void; +>test : (value: T | PromiseLike) => void +>value : T | PromiseLike +} + +declare let g1: (x: Foo2 | Bar2) => Promise; +>g1 : (x: Foo2 | Bar2) => Promise +>x : Foo2 | Bar2 + +declare let g2: (x: Foo2 | Bar2) => Promise; +>g2 : (x: Foo2 | Bar2) => Promise +>x : Foo2 | Bar2 + +g1 = g2; +>g1 = g2 : (x: Foo2 | Bar2) => Promise +>g1 : (x: Foo2 | Bar2) => Promise +>g2 : (x: Foo2 | Bar2) => Promise + +g2 = g1; +>g2 = g1 : (x: Foo2 | Bar2) => Promise +>g2 : (x: Foo2 | Bar2) => Promise +>g1 : (x: Foo2 | Bar2) => Promise + From ee623c1ae69b46774c2779c28c3fb438f3514072 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 25 Jul 2019 11:57:23 -0700 Subject: [PATCH 055/151] Add test case before change where config project is created just to remove it --- .../unittests/tsserver/inferredProjects.ts | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/testRunner/unittests/tsserver/inferredProjects.ts b/src/testRunner/unittests/tsserver/inferredProjects.ts index 0bc14809aaa..6882f2ed5c5 100644 --- a/src/testRunner/unittests/tsserver/inferredProjects.ts +++ b/src/testRunner/unittests/tsserver/inferredProjects.ts @@ -345,5 +345,68 @@ namespace ts.projectSystem { it("inferred projects per project root with case insensitive system", () => { verifyProjectRootWithCaseSensitivity(/*useCaseSensitiveFileNames*/ false); }); + + it("should still retain configured project created while opening the file", () => { + const projectRoot = "/user/username/projects/project"; + const appFile: File = { + path: `${projectRoot}/app.ts`, + content: `const app = 20;` + }; + const config: File = { + path: `${projectRoot}/tsconfig.json`, + content: "{}" + }; + const jsFile1: File = { + path: `${projectRoot}/jsFile1.js`, + content: `const jsFile1 = 10;` + }; + const jsFile2: File = { + path: `${projectRoot}/jsFile2.js`, + content: `const jsFile2 = 10;` + }; + const host = createServerHost([appFile, libFile, config, jsFile1, jsFile2]); + const projectService = createProjectService(host); + const originalSet = projectService.configuredProjects.set; + const originalDelete = projectService.configuredProjects.delete; + const configuredCreated = createMap(); + const configuredRemoved = createMap(); + projectService.configuredProjects.set = (key, value) => { + assert.isFalse(configuredCreated.has(key)); + configuredCreated.set(key, true); + return originalSet.call(projectService.configuredProjects, key, value); + }; + projectService.configuredProjects.delete = key => { + assert.isFalse(configuredRemoved.has(key)); + configuredRemoved.set(key, true); + return originalDelete.call(projectService.configuredProjects, key); + }; + + projectService.openClientFile(jsFile1.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [jsFile1.path, libFile.path]); + checkConfiguredProjectCreatedAndDeleted(); + + projectService.closeClientFile(jsFile1.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + projectService.openClientFile(jsFile2.path); + checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [jsFile2.path, libFile.path]); + checkConfiguredProjectCreatedAndDeleted(); + + projectService.openClientFile(jsFile1.path); + checkNumberOfProjects(projectService, { inferredProjects: 2 }); + checkProjectActualFiles(projectService.inferredProjects[0], [jsFile2.path, libFile.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [jsFile1.path, libFile.path]); + checkConfiguredProjectCreatedAndDeleted(); + + function checkConfiguredProjectCreatedAndDeleted() { + assert.equal(configuredCreated.size, 1); + assert.isTrue(configuredCreated.has(config.path)); + assert.equal(configuredRemoved.size, 1); + assert.isTrue(configuredRemoved.has(config.path)); + configuredCreated.clear(); + configuredRemoved.clear(); + } + }); }); } From 10ee85c98c9027321bc88fc8e42f4d759c7c0c63 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 25 Jul 2019 12:28:09 -0700 Subject: [PATCH 056/151] Retain the configured project opened during opening client file even if opened file isnt included in that project This helps not create and remove project on every open if tsconfig file isnt referenced by any open file --- src/server/editorServices.ts | 41 ++++++++++++++----- .../unittests/tsserver/configuredProjects.ts | 14 +++---- .../unittests/tsserver/inferredProjects.ts | 40 ++++++++++++++---- src/testRunner/unittests/tsserver/projects.ts | 18 ++++++-- 4 files changed, 83 insertions(+), 30 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index df9f0e3ee01..a25256a3aec 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -284,6 +284,10 @@ namespace ts.server { configFileErrors?: ReadonlyArray; } + interface AssignProjectResult extends OpenConfiguredProjectResult { + defaultConfigProject: ConfiguredProject | undefined; + } + interface FilePropertyReader { getFileName(f: T): string; getScriptKind(f: T, extraFileExtensions?: FileExtensionInfo[]): ScriptKind; @@ -2635,10 +2639,11 @@ namespace ts.server { return info; } - private assignProjectToOpenedScriptInfo(info: ScriptInfo): OpenConfiguredProjectResult { + private assignProjectToOpenedScriptInfo(info: ScriptInfo): AssignProjectResult { let configFileName: NormalizedPath | undefined; let configFileErrors: ReadonlyArray | undefined; let project: ConfiguredProject | ExternalProject | undefined = this.findExternalProjectContainingOpenScriptInfo(info); + let defaultConfigProject: ConfiguredProject | undefined; if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization configFileName = this.getConfigFileNameForFile(info); if (configFileName) { @@ -2659,6 +2664,7 @@ namespace ts.server { // Ensure project is ready to check if it contains opened script info updateProjectIfDirty(project); } + defaultConfigProject = project; } } @@ -2678,13 +2684,13 @@ namespace ts.server { this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path)); } Debug.assert(!info.isOrphan()); - return { configFileName, configFileErrors }; + return { configFileName, configFileErrors, defaultConfigProject }; } - private cleanupAfterOpeningFile() { + private cleanupAfterOpeningFile(toRetainConfigProjects: ConfiguredProject[] | ConfiguredProject | undefined) { // This was postponed from closeOpenFile to after opening next file, // so that we can reuse the project if we need to right away - this.removeOrphanConfiguredProjects(); + this.removeOrphanConfiguredProjects(toRetainConfigProjects); // Remove orphan inferred projects now that we have reused projects // We need to create a duplicate because we cant guarantee order after removal @@ -2705,14 +2711,22 @@ namespace ts.server { openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult { const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath); - const result = this.assignProjectToOpenedScriptInfo(info); - this.cleanupAfterOpeningFile(); + const { defaultConfigProject, ...result } = this.assignProjectToOpenedScriptInfo(info); + this.cleanupAfterOpeningFile(defaultConfigProject); this.telemetryOnOpenFile(info); return result; } - private removeOrphanConfiguredProjects() { + private removeOrphanConfiguredProjects(toRetainConfiguredProjects: ConfiguredProject[] | ConfiguredProject | undefined) { const toRemoveConfiguredProjects = cloneMap(this.configuredProjects); + if (toRetainConfiguredProjects) { + if (isArray(toRetainConfiguredProjects)) { + toRetainConfiguredProjects.forEach(retainConfiguredProject); + } + else { + retainConfiguredProject(toRetainConfiguredProjects); + } + } // Do not remove configured projects that are used as original projects of other this.inferredProjects.forEach(markOriginalProjectsAsUsed); @@ -2720,7 +2734,7 @@ namespace ts.server { this.configuredProjects.forEach(project => { // If project has open ref (there are more than zero references from external project/open file), keep it alive as well as any project it references if (project.hasOpenRef()) { - toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + retainConfiguredProject(project); markOriginalProjectsAsUsed(project); } else { @@ -2729,7 +2743,7 @@ namespace ts.server { if (ref) { const refProject = this.configuredProjects.get(ref.sourceFile.path); if (refProject && refProject.hasOpenRef()) { - toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + retainConfiguredProject(project); } } }); @@ -2744,6 +2758,10 @@ namespace ts.server { project.originalConfiguredProjects.forEach((_value, configuredProjectPath) => toRemoveConfiguredProjects.delete(configuredProjectPath)); } } + + function retainConfiguredProject(project: ConfiguredProject) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + } } private removeOrphanScriptInfos() { @@ -2886,8 +2904,9 @@ namespace ts.server { } // All the script infos now exist, so ok to go update projects for open files + let defaultConfigProjects: ConfiguredProject[] | undefined; if (openScriptInfos) { - openScriptInfos.forEach(info => this.assignProjectToOpenedScriptInfo(info)); + defaultConfigProjects = mapDefined(openScriptInfos, info => this.assignProjectToOpenedScriptInfo(info).defaultConfigProject); } // While closing files there could be open files that needed assigning new inferred projects, do it now @@ -2896,7 +2915,7 @@ namespace ts.server { } // Cleanup projects - this.cleanupAfterOpeningFile(); + this.cleanupAfterOpeningFile(defaultConfigProjects); // Telemetry forEach(openScriptInfos, info => this.telemetryOnOpenFile(info)); diff --git a/src/testRunner/unittests/tsserver/configuredProjects.ts b/src/testRunner/unittests/tsserver/configuredProjects.ts index a72c9924303..7d066cd9473 100644 --- a/src/testRunner/unittests/tsserver/configuredProjects.ts +++ b/src/testRunner/unittests/tsserver/configuredProjects.ts @@ -866,12 +866,12 @@ namespace ts.projectSystem { const projectService = createProjectService(host); projectService.openClientFile(file1.path); host.runQueuedTimeoutCallbacks(); - // Since there is no file open from configFile it would be closed - checkNumberOfConfiguredProjects(projectService, 0); - checkNumberOfInferredProjects(projectService, 1); + // Since file1 refers to config file as the default project, it needs to be kept alive + checkNumberOfProjects(projectService, { inferredProjects: 1, configuredProjects: 1 }); const inferredProject = projectService.inferredProjects[0]; assert.isTrue(inferredProject.containsFile(file1.path)); + assert.isFalse(projectService.configuredProjects.get(configFile.path)!.containsFile(file1.path)); }); it("should be able to handle @types if input file list is empty", () => { @@ -898,8 +898,8 @@ namespace ts.projectSystem { const projectService = createProjectService(host); projectService.openClientFile(f.path); - // Since no file from the configured project is open, it would be closed immediately - projectService.checkNumberOfProjects({ configuredProjects: 0, inferredProjects: 1 }); + // Since f refers to config file as the default project, it needs to be kept alive + projectService.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 }); }); it("should tolerate invalid include files that start in subDirectory", () => { @@ -924,8 +924,8 @@ namespace ts.projectSystem { const projectService = createProjectService(host); projectService.openClientFile(f.path); - // Since no file from the configured project is open, it would be closed immediately - projectService.checkNumberOfProjects({ configuredProjects: 0, inferredProjects: 1 }); + // Since f refers to config file as the default project, it needs to be kept alive + projectService.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 }); }); it("Changed module resolution reflected when specifying files list", () => { diff --git a/src/testRunner/unittests/tsserver/inferredProjects.ts b/src/testRunner/unittests/tsserver/inferredProjects.ts index 6882f2ed5c5..44ff8292acd 100644 --- a/src/testRunner/unittests/tsserver/inferredProjects.ts +++ b/src/testRunner/unittests/tsserver/inferredProjects.ts @@ -381,30 +381,54 @@ namespace ts.projectSystem { return originalDelete.call(projectService.configuredProjects, key); }; + // Do not remove config project when opening jsFile that is not present as part of config project projectService.openClientFile(jsFile1.path); - checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkNumberOfProjects(projectService, { inferredProjects: 1, configuredProjects: 1 }); checkProjectActualFiles(projectService.inferredProjects[0], [jsFile1.path, libFile.path]); - checkConfiguredProjectCreatedAndDeleted(); + const project = projectService.configuredProjects.get(config.path)!; + checkProjectActualFiles(project, [appFile.path, config.path, libFile.path]); + checkConfiguredProjectCreatedAndNotDeleted(); + // Do not remove config project when opening jsFile that is not present as part of config project projectService.closeClientFile(jsFile1.path); - checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkNumberOfProjects(projectService, { inferredProjects: 1, configuredProjects: 1 }); projectService.openClientFile(jsFile2.path); - checkNumberOfProjects(projectService, { inferredProjects: 1 }); + checkNumberOfProjects(projectService, { inferredProjects: 1, configuredProjects: 1 }); checkProjectActualFiles(projectService.inferredProjects[0], [jsFile2.path, libFile.path]); - checkConfiguredProjectCreatedAndDeleted(); + checkProjectActualFiles(project, [appFile.path, config.path, libFile.path]); + checkConfiguredProjectNotCreatedAndNotDeleted(); + // Do not remove config project when opening jsFile that is not present as part of config project projectService.openClientFile(jsFile1.path); + checkNumberOfProjects(projectService, { inferredProjects: 2, configuredProjects: 1 }); + checkProjectActualFiles(projectService.inferredProjects[0], [jsFile2.path, libFile.path]); + checkProjectActualFiles(projectService.inferredProjects[1], [jsFile1.path, libFile.path]); + checkProjectActualFiles(project, [appFile.path, config.path, libFile.path]); + checkConfiguredProjectNotCreatedAndNotDeleted(); + + // When opening file that doesnt fall back to the config file, we remove the config project + projectService.openClientFile(libFile.path); checkNumberOfProjects(projectService, { inferredProjects: 2 }); checkProjectActualFiles(projectService.inferredProjects[0], [jsFile2.path, libFile.path]); checkProjectActualFiles(projectService.inferredProjects[1], [jsFile1.path, libFile.path]); - checkConfiguredProjectCreatedAndDeleted(); + checkConfiguredProjectNotCreatedButDeleted(); - function checkConfiguredProjectCreatedAndDeleted() { + function checkConfiguredProjectCreatedAndNotDeleted() { assert.equal(configuredCreated.size, 1); assert.isTrue(configuredCreated.has(config.path)); + assert.equal(configuredRemoved.size, 0); + configuredCreated.clear(); + } + + function checkConfiguredProjectNotCreatedAndNotDeleted() { + assert.equal(configuredCreated.size, 0); + assert.equal(configuredRemoved.size, 0); + } + + function checkConfiguredProjectNotCreatedButDeleted() { + assert.equal(configuredCreated.size, 0); assert.equal(configuredRemoved.size, 1); assert.isTrue(configuredRemoved.has(config.path)); - configuredCreated.clear(); configuredRemoved.clear(); } }); diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index abb21669f8a..78d22615256 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -634,13 +634,17 @@ namespace ts.projectSystem { path: "/a/main.js", content: "var y = 1" }; + const f3 = { + path: "/main.js", + content: "var y = 1" + }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ compilerOptions: { allowJs: true } }) }; - const host = createServerHost([f1, f2, config]); + const host = createServerHost([f1, f2, f3, config]); const projectService = createProjectService(host); projectService.setHostConfiguration({ extraFileExtensions: [ @@ -652,13 +656,19 @@ namespace ts.projectSystem { projectService.checkNumberOfProjects({ configuredProjects: 1 }); checkProjectActualFiles(configuredProjectAt(projectService, 0), [f1.path, config.path]); - // Should close configured project with next file open + // Since f2 refers to config file as the default project, it needs to be kept alive projectService.closeClientFile(f1.path); - projectService.openClientFile(f2.path); + projectService.checkNumberOfProjects({ inferredProjects: 1, configuredProjects: 1 }); + assert.isDefined(projectService.configuredProjects.get(config.path)); + checkProjectActualFiles(projectService.inferredProjects[0], [f2.path]); + + // Should close configured project with next file open + projectService.closeClientFile(f2.path); + projectService.openClientFile(f3.path); projectService.checkNumberOfProjects({ inferredProjects: 1 }); assert.isUndefined(projectService.configuredProjects.get(config.path)); - checkProjectActualFiles(projectService.inferredProjects[0], [f2.path]); + checkProjectActualFiles(projectService.inferredProjects[0], [f3.path]); }); it("tsconfig script block support", () => { From 4c76bae8880d97d01847064cd98befba8f42028a Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 25 Jul 2019 14:03:17 -0700 Subject: [PATCH 057/151] Don't exclude non-anonymous object types in identity checks --- src/compiler/checker.ts | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 54c8d05e502..0f8326c1fac 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15500,7 +15500,7 @@ namespace ts { // First, infer between exactly matching source and target constituents and remove // the matching types. Types exactly match when they are identical or, in union // types, when the source is a literal and the target is the corresponding primitive. - const matching = target.flags & TypeFlags.Union ? isTypeOrBaseExactlyMatchedBy : isTypeExactlyMatchedBy; + const matching = target.flags & TypeFlags.Union ? isTypeOrBaseIdenticalTo : isTypeIdenticalTo; const [tempSources, tempTargets] = inferFromMatchingTypes((source).types, (target).types, matching); // Next, infer between closely matching source and target constituents and remove // the matching types. Types closely match when they are instantiations of the same @@ -15515,7 +15515,7 @@ namespace ts { else if (target.flags & TypeFlags.Union && !(target.flags & TypeFlags.EnumLiteral) || target.flags & TypeFlags.Intersection) { // This block of code is an optimized version of the block above for the simpler case // of a singleton source type. - const matching = target.flags & TypeFlags.Union ? isTypeOrBaseExactlyMatchedBy : isTypeExactlyMatchedBy; + const matching = target.flags & TypeFlags.Union ? isTypeOrBaseIdenticalTo : isTypeIdenticalTo; if (inferFromMatchingType(source, (target).types, matching)) return; if (inferFromMatchingType(source, (target).types, isTypeCloselyMatchedBy)) return; } @@ -15974,19 +15974,8 @@ namespace ts { } } - function isNonObjectOrAnonymousType(type: Type) { - // We exclude non-anonymous object types because some frameworks (e.g. Ember) rely on the ability to - // infer between types that don't witness their type variables. Such types would otherwise be eliminated - // because they appear identical. - return !(type.flags & TypeFlags.Object) || !!(getObjectFlags(type) & ObjectFlags.Anonymous); - } - - function isTypeExactlyMatchedBy(s: Type, t: Type) { - return s === t || isNonObjectOrAnonymousType(s) && isNonObjectOrAnonymousType(t) && isTypeIdenticalTo(s, t); - } - - function isTypeOrBaseExactlyMatchedBy(s: Type, t: Type) { - return isTypeExactlyMatchedBy(s, t) || !!(s.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) && isTypeIdenticalTo(getBaseTypeOfLiteralType(s), t); + function isTypeOrBaseIdenticalTo(s: Type, t: Type) { + return isTypeIdenticalTo(s, t) || !!(s.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) && isTypeIdenticalTo(getBaseTypeOfLiteralType(s), t); } function isTypeCloselyMatchedBy(s: Type, t: Type) { From 9647506d8c6dea0c2531f5f4867971e419799e1f Mon Sep 17 00:00:00 2001 From: Andrew Casey Date: Wed, 24 Jul 2019 15:57:46 -0700 Subject: [PATCH 058/151] Support classification of triple-slash references Note: not restricted to the element and attribute names that actually bind --- src/services/classifier.ts | 83 +++++++++++++++++++ .../syntacticClassificationsTripleSlash1.ts | 15 ++++ .../syntacticClassificationsTripleSlash10.ts | 13 +++ .../syntacticClassificationsTripleSlash11.ts | 15 ++++ .../syntacticClassificationsTripleSlash12.ts | 19 +++++ .../syntacticClassificationsTripleSlash13.ts | 16 ++++ .../syntacticClassificationsTripleSlash14.ts | 7 ++ .../syntacticClassificationsTripleSlash15.ts | 25 ++++++ .../syntacticClassificationsTripleSlash16.ts | 17 ++++ .../syntacticClassificationsTripleSlash2.ts | 16 ++++ .../syntacticClassificationsTripleSlash3.ts | 19 +++++ .../syntacticClassificationsTripleSlash4.ts | 8 ++ .../syntacticClassificationsTripleSlash5.ts | 9 ++ .../syntacticClassificationsTripleSlash6.ts | 10 +++ .../syntacticClassificationsTripleSlash7.ts | 10 +++ .../syntacticClassificationsTripleSlash8.ts | 10 +++ .../syntacticClassificationsTripleSlash9.ts | 10 +++ 17 files changed, 302 insertions(+) create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash1.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash10.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash11.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash12.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash13.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash14.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash15.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash16.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash2.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash3.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash4.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash5.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash6.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash7.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash8.ts create mode 100644 tests/cases/fourslash/syntacticClassificationsTripleSlash9.ts diff --git a/src/services/classifier.ts b/src/services/classifier.ts index f85a69681de..f1db477481f 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -683,6 +683,11 @@ namespace ts { return; } } + else if (kind === SyntaxKind.SingleLineCommentTrivia) { + if (tryClassifyTripleSlashComment(start, width)) { + return; + } + } // Simple comment. Just add as is. pushCommentRange(start, width); @@ -755,6 +760,84 @@ namespace ts { } } + function tryClassifyTripleSlashComment(start: number, width: number): boolean { + const tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im; + const attributeRegex = /(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img; + + const text = sourceFile.text.substr(start, width); + const match = tripleSlashXMLCommentRegEx.exec(text); + if (!match) { + return false; + } + + let pos = start; + + pushCommentRange(pos, match[1].length); // /// + pos += match[1].length; + + pushClassification(pos, match[2].length, ClassificationType.punctuation); // < + pos += match[2].length; + + if (!match[3]) { + return true; + } + + pushClassification(pos, match[3].length, ClassificationType.jsxSelfClosingTagName); // element name + pos += match[3].length; + + const attrText = match[4]; + let attrPos = pos; + while (true) { + const attrMatch = attributeRegex.exec(attrText); + if (!attrMatch) { + break; + } + + const newAttrPos = pos + attrMatch.index; + if (newAttrPos > attrPos) { + pushCommentRange(attrPos, newAttrPos - attrPos); + attrPos = newAttrPos; + } + + pushClassification(attrPos, attrMatch[1].length, ClassificationType.jsxAttribute); // attribute name + attrPos += attrMatch[1].length; + + if (attrMatch[2].length) { + pushCommentRange(attrPos, attrMatch[2].length); // whitespace + attrPos += attrMatch[2].length; + } + + pushClassification(attrPos, attrMatch[3].length, ClassificationType.operator); // = + attrPos += attrMatch[3].length; + + if (attrMatch[4].length) { + pushCommentRange(attrPos, attrMatch[4].length); // whitespace + attrPos += attrMatch[4].length; + } + + pushClassification(attrPos, attrMatch[5].length, ClassificationType.jsxAttributeStringLiteralValue); // attribute value + attrPos += attrMatch[5].length; + } + + pos += match[4].length; + + if (pos > attrPos) { + pushCommentRange(attrPos, pos - attrPos); + } + + if (match[5]) { + pushClassification(pos, match[5].length, ClassificationType.punctuation); // /> + pos += match[5].length; + } + + const end = start + width; + if (pos < end) { + pushCommentRange(pos, end - pos); + } + + return true; + } + function processJSDocTemplateTag(tag: JSDocTemplateTag) { for (const child of tag.getChildren()) { processElement(child); diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash1.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash1.ts new file mode 100644 index 00000000000..13c27669ad5 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash1.ts @@ -0,0 +1,15 @@ +/// + +//// /// + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module.ts\""), + c.comment(" "), + c.punctuation("/>")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash10.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash10.ts new file mode 100644 index 00000000000..d1bb681b92e --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash10.ts @@ -0,0 +1,13 @@ +/// + +//// /// + +//// /// + +//// /// + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module.ts\""), + c.comment(" bad "), + c.jsxAttribute("types"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"node\""), + c.comment(" "), + c.punctuation("/>")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash13.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash13.ts new file mode 100644 index 00000000000..182b01f7560 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash13.ts @@ -0,0 +1,16 @@ +/// + +//// /// trailing + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module.ts\""), + c.comment(" "), + c.punctuation("/>"), + c.comment(" trailing")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash14.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash14.ts new file mode 100644 index 00000000000..a7d16fea02c --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash14.ts @@ -0,0 +1,7 @@ +/// + +//// /// nonElement + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// nonElement")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash15.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash15.ts new file mode 100644 index 00000000000..8ec5ebbea5d --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash15.ts @@ -0,0 +1,25 @@ +/// + +//// /// +//// /// + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module1.ts\""), + c.comment(" "), + c.punctuation("/>"), + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module2.ts\""), + c.comment(" "), + c.punctuation("/>")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash16.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash16.ts new file mode 100644 index 00000000000..1dbee22cb59 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash16.ts @@ -0,0 +1,17 @@ +/// + +//// /// +//// 1 + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module.ts\""), + c.comment(" "), + c.punctuation("/>"), + c.numericLiteral("1")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash2.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash2.ts new file mode 100644 index 00000000000..278d66dcb4a --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash2.ts @@ -0,0 +1,16 @@ +/// + +//// /// + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("///"), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.comment(" "), + c.operator("="), + c.comment(" "), + c.jsxAttributeStringLiteralValue("\"./module.ts\""), + c.punctuation("/>")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash3.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash3.ts new file mode 100644 index 00000000000..11d3b2462be --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash3.ts @@ -0,0 +1,19 @@ +/// + +//// /// + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<"), + c.jsxSelfClosingTagName("reference"), + c.comment(" "), + c.jsxAttribute("path"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"./module.ts\""), + c.comment(" "), + c.jsxAttribute("types"), + c.operator("="), + c.jsxAttributeStringLiteralValue("\"node\""), + c.comment(" "), + c.punctuation("/>")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash4.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash4.ts new file mode 100644 index 00000000000..e656c811377 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash4.ts @@ -0,0 +1,8 @@ +/// + +//// /// < + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/// "), + c.punctuation("<")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsTripleSlash5.ts b/tests/cases/fourslash/syntacticClassificationsTripleSlash5.ts new file mode 100644 index 00000000000..c6f1de38f28 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsTripleSlash5.ts @@ -0,0 +1,9 @@ +/// + +//// /// + +//// /// + +//// /// + +//// /// + +//// /// Date: Thu, 25 Jul 2019 17:10:31 -0400 Subject: [PATCH 059/151] Handle namepaths inside JSDoc type expressions a bit better - fixes #31298 --- src/compiler/parser.ts | 8 +++ src/compiler/types.ts | 7 +++ .../reference/api/tsserverlibrary.d.ts | 57 ++++++++++--------- tests/baselines/reference/api/typescript.d.ts | 57 ++++++++++--------- .../noAssertForUnparseableTypedefs.errors.txt | 9 +-- .../fourslash/jsDocDontBreakWithNamespaces.ts | 17 ++++++ 6 files changed, 97 insertions(+), 58 deletions(-) create mode 100644 tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 254be93000b..9762302b7a2 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2429,8 +2429,16 @@ namespace ts { function parseJSDocType(): TypeNode { scanner.setInJSDocType(true); const dotdotdot = parseOptionalToken(SyntaxKind.DotDotDotToken); + const moduleSpecifier = parseOptionalToken(SyntaxKind.ModuleKeyword); let type = parseTypeOrTypePredicate(); scanner.setInJSDocType(false); + if (moduleSpecifier) { + const moduleTag = createNode(SyntaxKind.JSDocNamepathType, moduleSpecifier.pos) as JSDocNamepathType; + while (token() !== SyntaxKind.CloseBraceToken && token() !== SyntaxKind.EndOfFileToken) { + nextTokenJSDoc(); + } + type = finishNode(moduleTag); + } if (dotdotdot) { const variadic = createNode(SyntaxKind.JSDocVariadicType, dotdotdot.pos) as JSDocVariadicType; variadic.type = type; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 67c85147aed..e1461071e20 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -455,6 +455,8 @@ namespace ts { JSDocOptionalType, JSDocFunctionType, JSDocVariadicType, + // https://jsdoc.app/about-namepaths.html + JSDocNamepathType, JSDocComment, JSDocTypeLiteral, JSDocSignature, @@ -2430,6 +2432,11 @@ namespace ts { type: TypeNode; } + export interface JSDocNamepathType extends JSDocType { + kind: SyntaxKind.JSDocNamepathType; + type: TypeNode; + } + export type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; export interface JSDoc extends Node { diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index c2bad61505b..549cb6368f9 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -374,29 +374,30 @@ declare namespace ts { JSDocOptionalType = 294, JSDocFunctionType = 295, JSDocVariadicType = 296, - JSDocComment = 297, - JSDocTypeLiteral = 298, - JSDocSignature = 299, - JSDocTag = 300, - JSDocAugmentsTag = 301, - JSDocAuthorTag = 302, - JSDocClassTag = 303, - JSDocCallbackTag = 304, - JSDocEnumTag = 305, - JSDocParameterTag = 306, - JSDocReturnTag = 307, - JSDocThisTag = 308, - JSDocTypeTag = 309, - JSDocTemplateTag = 310, - JSDocTypedefTag = 311, - JSDocPropertyTag = 312, - SyntaxList = 313, - NotEmittedStatement = 314, - PartiallyEmittedExpression = 315, - CommaListExpression = 316, - MergeDeclarationMarker = 317, - EndOfDeclarationMarker = 318, - Count = 319, + JSDocNamepathType = 297, + JSDocComment = 298, + JSDocTypeLiteral = 299, + JSDocSignature = 300, + JSDocTag = 301, + JSDocAugmentsTag = 302, + JSDocAuthorTag = 303, + JSDocClassTag = 304, + JSDocCallbackTag = 305, + JSDocEnumTag = 306, + JSDocParameterTag = 307, + JSDocReturnTag = 308, + JSDocThisTag = 309, + JSDocTypeTag = 310, + JSDocTemplateTag = 311, + JSDocTypedefTag = 312, + JSDocPropertyTag = 313, + SyntaxList = 314, + NotEmittedStatement = 315, + PartiallyEmittedExpression = 316, + CommaListExpression = 317, + MergeDeclarationMarker = 318, + EndOfDeclarationMarker = 319, + Count = 320, FirstAssignment = 60, LastAssignment = 72, FirstCompoundAssignment = 61, @@ -423,9 +424,9 @@ declare namespace ts { LastBinaryOperator = 72, FirstNode = 149, FirstJSDocNode = 289, - LastJSDocNode = 312, - FirstJSDocTagNode = 300, - LastJSDocTagNode = 312, + LastJSDocNode = 313, + FirstJSDocTagNode = 301, + LastJSDocTagNode = 313, } enum NodeFlags { None = 0, @@ -1558,6 +1559,10 @@ declare namespace ts { kind: SyntaxKind.JSDocVariadicType; type: TypeNode; } + interface JSDocNamepathType extends JSDocType { + kind: SyntaxKind.JSDocNamepathType; + type: TypeNode; + } type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 7a2559bbc22..935aff356f8 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -374,29 +374,30 @@ declare namespace ts { JSDocOptionalType = 294, JSDocFunctionType = 295, JSDocVariadicType = 296, - JSDocComment = 297, - JSDocTypeLiteral = 298, - JSDocSignature = 299, - JSDocTag = 300, - JSDocAugmentsTag = 301, - JSDocAuthorTag = 302, - JSDocClassTag = 303, - JSDocCallbackTag = 304, - JSDocEnumTag = 305, - JSDocParameterTag = 306, - JSDocReturnTag = 307, - JSDocThisTag = 308, - JSDocTypeTag = 309, - JSDocTemplateTag = 310, - JSDocTypedefTag = 311, - JSDocPropertyTag = 312, - SyntaxList = 313, - NotEmittedStatement = 314, - PartiallyEmittedExpression = 315, - CommaListExpression = 316, - MergeDeclarationMarker = 317, - EndOfDeclarationMarker = 318, - Count = 319, + JSDocNamepathType = 297, + JSDocComment = 298, + JSDocTypeLiteral = 299, + JSDocSignature = 300, + JSDocTag = 301, + JSDocAugmentsTag = 302, + JSDocAuthorTag = 303, + JSDocClassTag = 304, + JSDocCallbackTag = 305, + JSDocEnumTag = 306, + JSDocParameterTag = 307, + JSDocReturnTag = 308, + JSDocThisTag = 309, + JSDocTypeTag = 310, + JSDocTemplateTag = 311, + JSDocTypedefTag = 312, + JSDocPropertyTag = 313, + SyntaxList = 314, + NotEmittedStatement = 315, + PartiallyEmittedExpression = 316, + CommaListExpression = 317, + MergeDeclarationMarker = 318, + EndOfDeclarationMarker = 319, + Count = 320, FirstAssignment = 60, LastAssignment = 72, FirstCompoundAssignment = 61, @@ -423,9 +424,9 @@ declare namespace ts { LastBinaryOperator = 72, FirstNode = 149, FirstJSDocNode = 289, - LastJSDocNode = 312, - FirstJSDocTagNode = 300, - LastJSDocTagNode = 312, + LastJSDocNode = 313, + FirstJSDocTagNode = 301, + LastJSDocTagNode = 313, } enum NodeFlags { None = 0, @@ -1558,6 +1559,10 @@ declare namespace ts { kind: SyntaxKind.JSDocVariadicType; type: TypeNode; } + interface JSDocNamepathType extends JSDocType { + kind: SyntaxKind.JSDocNamepathType; + type: TypeNode; + } type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; diff --git a/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt b/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt index b131c8adac0..a0b1f6210ba 100644 --- a/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt +++ b/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt @@ -1,14 +1,11 @@ -tests/cases/conformance/jsdoc/bug26693.js(1,15): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/conformance/jsdoc/bug26693.js(1,21): error TS1005: '}' expected. +tests/cases/conformance/jsdoc/bug26693.js(1,21): error TS1110: Type expected. tests/cases/conformance/jsdoc/bug26693.js(2,22): error TS2307: Cannot find module 'nope'. -==== tests/cases/conformance/jsdoc/bug26693.js (3 errors) ==== +==== tests/cases/conformance/jsdoc/bug26693.js (2 errors) ==== /** @typedef {module:locale} hi */ - ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ -!!! error TS1005: '}' expected. +!!! error TS1110: Type expected. import { nope } from 'nope'; ~~~~~~ !!! error TS2307: Cannot find module 'nope'. diff --git a/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts b/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts new file mode 100644 index 00000000000..7807d5d30d1 --- /dev/null +++ b/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts @@ -0,0 +1,17 @@ +/// +// @allowJs: true +// @Filename: 31298.js +/////** +//// * @returns {module:@nodefuel/web~Webserver~wsServer#hello} Websocket server object +//// */ +////function foo() { } +////foo(''/**/); + +verify.signatureHelp({ + marker: "", + text: "foo(): any", + docComment: "", + tags: [ + { name: "returns", text: "Websocket server object" }, + ], +}); From 599e36a0685fbeebddc00e8cb36b76fb52b9f0c8 Mon Sep 17 00:00:00 2001 From: Jesse Trinity <42591254+jessetrinity@users.noreply.github.com> Date: Thu, 25 Jul 2019 21:29:12 -0700 Subject: [PATCH 060/151] Decrement line ends if they end with a carriage return. (#31220) * Decrement line ends if they end with a carriage return. * Changed handling of newlines and inlined regex operation. * fixed misname of hintSpan * added tests * revert inline of regex match and use getLineEndOfPosition * fixed lint error and changed a silly thing in tests --- src/services/outliningElementsCollector.ts | 5 ++--- .../unittests/services/hostNewLineSupport.ts | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index a23eddf0628..6e5e2b963e8 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -71,9 +71,8 @@ namespace ts.OutliningElementsCollector { function addRegionOutliningSpans(sourceFile: SourceFile, out: Push): void { const regions: OutliningSpan[] = []; const lineStarts = sourceFile.getLineStarts(); - for (let i = 0; i < lineStarts.length; i++) { - const currentLineStart = lineStarts[i]; - const lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; + for (const currentLineStart of lineStarts) { + const lineEnd = sourceFile.getLineEndOfPosition(currentLineStart); const lineText = sourceFile.text.substring(currentLineStart, lineEnd); const result = isRegionDelimiter(lineText); if (!result || isInComment(sourceFile, currentLineStart)) { diff --git a/src/testRunner/unittests/services/hostNewLineSupport.ts b/src/testRunner/unittests/services/hostNewLineSupport.ts index cafe4813431..48bc124f3bc 100644 --- a/src/testRunner/unittests/services/hostNewLineSupport.ts +++ b/src/testRunner/unittests/services/hostNewLineSupport.ts @@ -38,6 +38,18 @@ namespace ts { verifyNewLines(content, { newLine: NewLineKind.LineFeed }); } + function verifyOutliningSpanNewLines(content: string, options: CompilerOptions) { + const ls = testLSWithFiles(options, [{ + content, + fileOptions: {}, + unitName: "input.ts" + }]); + const span = ls.getOutliningSpans("input.ts")[0]; + const textAfterSpanCollapse = content.substring(span.textSpan.start + span.textSpan.length); + assert(textAfterSpanCollapse.match(options.newLine === NewLineKind.CarriageReturnLineFeed ? /\r\n/ : /[^\r]\n/), "expected to find appropriate newlines"); + assert(!textAfterSpanCollapse.match(options.newLine === NewLineKind.CarriageReturnLineFeed ? /[^\r]\n/ : /\r\n/), "expected not to find inappropriate newlines"); + } + it("should exist and respect provided compiler options", () => { verifyBothNewLines(` function foo() { @@ -45,5 +57,15 @@ namespace ts { } `); }); + + it("should respect CRLF line endings around outlining spans", () => { + verifyOutliningSpanNewLines("// comment not included\r\n// #region name\r\nlet x: string = \"x\";\r\n// #endregion name\r\n", + { newLine: NewLineKind.CarriageReturnLineFeed }); + }); + + it("should respect LF line endings around outlining spans", () => { + verifyOutliningSpanNewLines("// comment not included\n// #region name\nlet x: string = \"x\";\n// #endregion name\n\n", + { newLine: NewLineKind.LineFeed }); + }); }); } From 00f41e5693e55ede6a243b8fe0f4d982081ef2dd Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Jul 2019 11:03:31 -0700 Subject: [PATCH 061/151] Less aggressive reduction of intersection types --- src/compiler/checker.ts | 70 +++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0f8326c1fac..8ef7b3453a2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15310,7 +15310,7 @@ namespace ts { objectFlags & ObjectFlags.Reference && forEach((type).typeArguments, couldContainTypeVariables) || objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || objectFlags & ObjectFlags.Mapped || - type.flags & TypeFlags.UnionOrIntersection && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & TypeFlags.UnionOrIntersection && !(type.flags & TypeFlags.EnumLiteral) && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type: UnionOrIntersectionType): boolean { @@ -15487,37 +15487,47 @@ namespace ts { inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments!, getAliasVariances(source.aliasSymbol)); return; } - if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && !(source.flags & TypeFlags.EnumLiteral && target.flags & TypeFlags.EnumLiteral) || - source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) { - // Source and target are both unions or both intersections. If source and target - // are the same type, just relate each constituent type to itself. - if (source === target) { - for (const t of (source).types) { - inferFromTypes(t, t); - } - return; + if (source === target && source.flags & TypeFlags.UnionOrIntersection) { + // When source and target are the same union or intersection type, just relate each constituent + // type to itself. + for (const t of (source).types) { + inferFromTypes(t, t); } - // First, infer between exactly matching source and target constituents and remove - // the matching types. Types exactly match when they are identical or, in union - // types, when the source is a literal and the target is the corresponding primitive. - const matching = target.flags & TypeFlags.Union ? isTypeOrBaseIdenticalTo : isTypeIdenticalTo; - const [tempSources, tempTargets] = inferFromMatchingTypes((source).types, (target).types, matching); - // Next, infer between closely matching source and target constituents and remove - // the matching types. Types closely match when they are instantiations of the same - // object type or instantiations of the same type alias. - const [sources, targets] = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy); - if (sources.length === 0 || targets.length === 0) { - return; - } - source = source.flags & TypeFlags.Union ? getUnionType(sources) : getIntersectionType(sources); - target = target.flags & TypeFlags.Union ? getUnionType(targets) : getIntersectionType(targets); + return; } - else if (target.flags & TypeFlags.Union && !(target.flags & TypeFlags.EnumLiteral) || target.flags & TypeFlags.Intersection) { - // This block of code is an optimized version of the block above for the simpler case - // of a singleton source type. - const matching = target.flags & TypeFlags.Union ? isTypeOrBaseIdenticalTo : isTypeIdenticalTo; - if (inferFromMatchingType(source, (target).types, matching)) return; - if (inferFromMatchingType(source, (target).types, isTypeCloselyMatchedBy)) return; + if (target.flags & TypeFlags.Union) { + if (source.flags & TypeFlags.Union) { + // First, infer between identically matching source and target constituents and remove the + // matching types. + const [tempSources, tempTargets] = inferFromMatchingTypes((source).types, (target).types, isTypeOrBaseIdenticalTo); + // Next, infer between closely matching source and target constituents and remove + // the matching types. Types closely match when they are instantiations of the same + // object type or instantiations of the same type alias. + const [sources, targets] = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy); + if (sources.length === 0 || targets.length === 0) { + return; + } + source = getUnionType(sources); + target = getUnionType(targets); + } + else { + if (inferFromMatchingType(source, (target).types, isTypeOrBaseIdenticalTo)) return; + if (inferFromMatchingType(source, (target).types, isTypeCloselyMatchedBy)) return; + } + } + else if (target.flags & TypeFlags.Intersection && some((target).types, t => !!getInferenceInfoForType(t))) { + if (source.flags & TypeFlags.Intersection) { + // Infer between identically matching source and target constituents and remove the matching types. + const [sources, targets] = inferFromMatchingTypes((source).types, (target).types, isTypeIdenticalTo); + if (sources.length === 0 || targets.length === 0) { + return; + } + source = getIntersectionType(sources); + target = getIntersectionType(targets); + } + else if (!(source.flags & TypeFlags.Union)) { + if (inferFromMatchingType(source, (target).types, isTypeIdenticalTo)) return; + } } else if (target.flags & (TypeFlags.IndexedAccess | TypeFlags.Substitution)) { target = getActualTypeVariable(target); From bb87332e73a1024dd3aa1b0fef18575cb504057d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Jul 2019 13:12:44 -0700 Subject: [PATCH 062/151] Add more comments --- src/compiler/checker.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8ef7b3453a2..a69751673f6 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15516,6 +15516,10 @@ namespace ts { } } else if (target.flags & TypeFlags.Intersection && some((target).types, t => !!getInferenceInfoForType(t))) { + // We reduce intersection types only when they contain naked type parameters. For example, when + // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and + // infer { extra: any } for T. But when inferring to 'string[] & Iterable' we want to keep the + // string[] on the source side and infer string for T. if (source.flags & TypeFlags.Intersection) { // Infer between identically matching source and target constituents and remove the matching types. const [sources, targets] = inferFromMatchingTypes((source).types, (target).types, isTypeIdenticalTo); From ec38799e2a1a9df776882e20d89604c85ec3015f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Jul 2019 13:17:00 -0700 Subject: [PATCH 063/151] Add more tests --- .../unionAndIntersectionInference3.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts index 17057de2b84..d64b1973695 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts @@ -40,3 +40,17 @@ declare let g2: (x: Foo2 | Bar2) => Promise; g1 = g2; g2 = g1; + +// Repro from #32572 + +declare function foo1(obj: string[] & Iterable): T; +declare function foo2(obj: string[] & T): T; + +declare let sa: string[]; +declare let sx: string[] & { extra: number }; + +let x1 = foo1(sa); // string +let y1 = foo1(sx); // string + +let x2 = foo2(sa); // unknown +let y2 = foo2(sx); // { extra: number } From 1ea4008120a20c4cca416af2096c5f3a46da7063 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Jul 2019 13:17:06 -0700 Subject: [PATCH 064/151] Accept new baselines --- .../unionAndIntersectionInference3.js | 18 ++++++++ .../unionAndIntersectionInference3.symbols | 44 +++++++++++++++++++ .../unionAndIntersectionInference3.types | 41 +++++++++++++++++ 3 files changed, 103 insertions(+) diff --git a/tests/baselines/reference/unionAndIntersectionInference3.js b/tests/baselines/reference/unionAndIntersectionInference3.js index c9f5cffa1f7..415d98220a5 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.js +++ b/tests/baselines/reference/unionAndIntersectionInference3.js @@ -38,6 +38,20 @@ declare let g2: (x: Foo2 | Bar2) => Promise; g1 = g2; g2 = g1; + +// Repro from #32572 + +declare function foo1(obj: string[] & Iterable): T; +declare function foo2(obj: string[] & T): T; + +declare let sa: string[]; +declare let sx: string[] & { extra: number }; + +let x1 = foo1(sa); // string +let y1 = foo1(sx); // string + +let x2 = foo2(sa); // unknown +let y2 = foo2(sx); // { extra: number } //// [unionAndIntersectionInference3.js] @@ -52,3 +66,7 @@ f1 = f2; f2 = f1; g1 = g2; g2 = g1; +let x1 = foo1(sa); // string +let y1 = foo1(sx); // string +let x2 = foo2(sa); // unknown +let y2 = foo2(sx); // { extra: number } diff --git a/tests/baselines/reference/unionAndIntersectionInference3.symbols b/tests/baselines/reference/unionAndIntersectionInference3.symbols index b854ee1ce42..1d237951b4f 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.symbols +++ b/tests/baselines/reference/unionAndIntersectionInference3.symbols @@ -161,3 +161,47 @@ g2 = g1; >g2 : Symbol(g2, Decl(unionAndIntersectionInference3.ts, 35, 11)) >g1 : Symbol(g1, Decl(unionAndIntersectionInference3.ts, 34, 11)) +// Repro from #32572 + +declare function foo1(obj: string[] & Iterable): T; +>foo1 : Symbol(foo1, Decl(unionAndIntersectionInference3.ts, 38, 8)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 42, 22)) +>obj : Symbol(obj, Decl(unionAndIntersectionInference3.ts, 42, 25)) +>Iterable : Symbol(Iterable, Decl(lib.es2015.iterable.d.ts, --, --)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 42, 22)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 42, 22)) + +declare function foo2(obj: string[] & T): T; +>foo2 : Symbol(foo2, Decl(unionAndIntersectionInference3.ts, 42, 57)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 43, 22)) +>obj : Symbol(obj, Decl(unionAndIntersectionInference3.ts, 43, 25)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 43, 22)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 43, 22)) + +declare let sa: string[]; +>sa : Symbol(sa, Decl(unionAndIntersectionInference3.ts, 45, 11)) + +declare let sx: string[] & { extra: number }; +>sx : Symbol(sx, Decl(unionAndIntersectionInference3.ts, 46, 11)) +>extra : Symbol(extra, Decl(unionAndIntersectionInference3.ts, 46, 28)) + +let x1 = foo1(sa); // string +>x1 : Symbol(x1, Decl(unionAndIntersectionInference3.ts, 48, 3)) +>foo1 : Symbol(foo1, Decl(unionAndIntersectionInference3.ts, 38, 8)) +>sa : Symbol(sa, Decl(unionAndIntersectionInference3.ts, 45, 11)) + +let y1 = foo1(sx); // string +>y1 : Symbol(y1, Decl(unionAndIntersectionInference3.ts, 49, 3)) +>foo1 : Symbol(foo1, Decl(unionAndIntersectionInference3.ts, 38, 8)) +>sx : Symbol(sx, Decl(unionAndIntersectionInference3.ts, 46, 11)) + +let x2 = foo2(sa); // unknown +>x2 : Symbol(x2, Decl(unionAndIntersectionInference3.ts, 51, 3)) +>foo2 : Symbol(foo2, Decl(unionAndIntersectionInference3.ts, 42, 57)) +>sa : Symbol(sa, Decl(unionAndIntersectionInference3.ts, 45, 11)) + +let y2 = foo2(sx); // { extra: number } +>y2 : Symbol(y2, Decl(unionAndIntersectionInference3.ts, 52, 3)) +>foo2 : Symbol(foo2, Decl(unionAndIntersectionInference3.ts, 42, 57)) +>sx : Symbol(sx, Decl(unionAndIntersectionInference3.ts, 46, 11)) + diff --git a/tests/baselines/reference/unionAndIntersectionInference3.types b/tests/baselines/reference/unionAndIntersectionInference3.types index acbca0a1eae..fb507474321 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.types +++ b/tests/baselines/reference/unionAndIntersectionInference3.types @@ -94,3 +94,44 @@ g2 = g1; >g2 : (x: Foo2 | Bar2) => Promise >g1 : (x: Foo2 | Bar2) => Promise +// Repro from #32572 + +declare function foo1(obj: string[] & Iterable): T; +>foo1 : (obj: string[] & Iterable) => T +>obj : string[] & Iterable + +declare function foo2(obj: string[] & T): T; +>foo2 : (obj: string[] & T) => T +>obj : string[] & T + +declare let sa: string[]; +>sa : string[] + +declare let sx: string[] & { extra: number }; +>sx : string[] & { extra: number; } +>extra : number + +let x1 = foo1(sa); // string +>x1 : string +>foo1(sa) : string +>foo1 : (obj: string[] & Iterable) => T +>sa : string[] + +let y1 = foo1(sx); // string +>y1 : string +>foo1(sx) : string +>foo1 : (obj: string[] & Iterable) => T +>sx : string[] & { extra: number; } + +let x2 = foo2(sa); // unknown +>x2 : unknown +>foo2(sa) : unknown +>foo2 : (obj: string[] & T) => T +>sa : string[] + +let y2 = foo2(sx); // { extra: number } +>y2 : { extra: number; } +>foo2(sx) : { extra: number; } +>foo2 : (obj: string[] & T) => T +>sx : string[] & { extra: number; } + From 2a4930f4ec75e8accd78744bd02b608d0cef9e4d Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 26 Jul 2019 13:57:22 -0700 Subject: [PATCH 065/151] Bind a jsdoc enum as SymbolFlags.TypeAlias and not SymbolFlags.Enum (#32520) * Bind a jsdoc enum as SymbolFlags.TypeAlias and not SymbolFlags.Enum * Actually include an @enum tag as a declaration * Add enum tag refs into a couple more syntax kind lists * accept symbol baseline update --- src/compiler/binder.ts | 21 +++++++------ src/compiler/checker.ts | 30 +++++++------------ src/compiler/types.ts | 3 +- src/compiler/utilities.ts | 10 ++++--- src/harness/typeWriter.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 3 +- tests/baselines/reference/api/typescript.d.ts | 3 +- tests/baselines/reference/enumTag.symbols | 16 +++++----- .../enumTagCircularReference.errors.txt | 6 ++-- .../enumTagCircularReference.symbols | 2 +- .../reference/enumTagImported.symbols | 2 +- .../enumTagUseBeforeDefCrash.symbols | 2 +- .../reference/enumTagUseBeforeDefCrash.types | 2 +- tests/cases/fourslash/findAllRefs_jsEnum.ts | 2 +- tests/cases/fourslash/quickInfoJsdocEnum.ts | 5 ++-- 15 files changed, 52 insertions(+), 57 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 38d5ed24eae..d18ab45a347 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -120,7 +120,7 @@ namespace ts { let thisParentContainer: Node; // Container one level up let blockScopeContainer: Node; let lastContainer: Node; - let delayedTypeAliases: (JSDocTypedefTag | JSDocCallbackTag)[]; + let delayedTypeAliases: (JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag)[]; let seenThisKeyword: boolean; // state used by control flow analysis @@ -732,7 +732,8 @@ namespace ts { break; case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: - bindJSDocTypeAlias(node as JSDocTypedefTag | JSDocCallbackTag); + case SyntaxKind.JSDocEnumTag: + bindJSDocTypeAlias(node as JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case SyntaxKind.SourceFile: { @@ -1436,9 +1437,9 @@ namespace ts { } } - function bindJSDocTypeAlias(node: JSDocTypedefTag | JSDocCallbackTag) { + function bindJSDocTypeAlias(node: JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag) { node.tagName.parent = node; - if (node.fullName) { + if (node.kind !== SyntaxKind.JSDocEnumTag && node.fullName) { setParentPointers(node, node.fullName); } } @@ -1805,7 +1806,7 @@ namespace ts { currentFlow = { flags: FlowFlags.Start }; parent = typeAlias; bind(typeAlias.typeExpression); - if (!typeAlias.fullName || typeAlias.fullName.kind === SyntaxKind.Identifier) { + if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === SyntaxKind.Identifier) { parent = typeAlias.parent; bindBlockScopedDeclaration(typeAlias, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); } @@ -2319,7 +2320,8 @@ namespace ts { return declareSymbolAndAddToSymbolTable(propTag, flags, SymbolFlags.PropertyExcludes); case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: - return (delayedTypeAliases || (delayedTypeAliases = [])).push(node as JSDocTypedefTag | JSDocCallbackTag); + case SyntaxKind.JSDocEnumTag: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node as JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag); } } @@ -2766,11 +2768,8 @@ namespace ts { } if (!isBindingPattern(node.name)) { - const isEnum = isInJSFile(node) && !!getJSDocEnumTag(node); - const enumFlags = (isEnum ? SymbolFlags.RegularEnum : SymbolFlags.None); - const enumExcludes = (isEnum ? SymbolFlags.RegularEnumExcludes : SymbolFlags.None); if (isBlockOrCatchScoped(node)) { - bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable | enumFlags, SymbolFlags.BlockScopedVariableExcludes | enumExcludes); + bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes); } else if (isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -2785,7 +2784,7 @@ namespace ts { declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); } else { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable | enumFlags, SymbolFlags.FunctionScopedVariableExcludes | enumExcludes); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.FunctionScopedVariableExcludes); } } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2f466267f9d..834fb3eccfa 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1680,6 +1680,7 @@ namespace ts { break; case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: + case SyntaxKind.JSDocEnumTag: // js type aliases do not resolve names from their host, so skip past it location = getJSDocHost(location); break; @@ -2025,7 +2026,7 @@ namespace ts { // Block-scoped variables cannot be used before their definition const declaration = find( result.declarations, - d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration) || isInJSFile(d) && !!getJSDocEnumTag(d)); + d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration)); if (declaration === undefined) return Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); @@ -4851,6 +4852,7 @@ namespace ts { switch (node.kind) { case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocTypedefTag: + case SyntaxKind.JSDocEnumTag: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && isSourceFile(node.parent.parent.parent)); @@ -6156,6 +6158,7 @@ namespace ts { case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.JSDocTemplateTag: case SyntaxKind.JSDocTypedefTag: + case SyntaxKind.JSDocEnumTag: case SyntaxKind.JSDocCallbackTag: case SyntaxKind.MappedType: case SyntaxKind.ConditionalType: @@ -6489,8 +6492,10 @@ namespace ts { return errorType; } - const declaration = find(symbol.declarations, d => - isJSDocTypeAlias(d) || d.kind === SyntaxKind.TypeAliasDeclaration); + const declaration = find(symbol.declarations, isTypeAlias); + if (!declaration) { + return Debug.fail("Type alias symbol with no valid declaration found"); + } const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -6507,7 +6512,7 @@ namespace ts { } else { type = errorType; - error(declaration.name, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + error(isJSDocEnumTag(declaration) ? declaration : declaration.name || declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } links.declaredType = type; } @@ -9159,21 +9164,6 @@ namespace ts { return type; } - // JS enums are 'string' or 'number', not an enum type. - const enumTag = isInJSFile(node) && symbol.valueDeclaration && getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag) { - const links = getNodeLinks(enumTag); - if (!pushTypeResolution(enumTag, TypeSystemPropertyName.EnumTagType)) { - return errorType; - } - let type = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; - if (!popTypeResolution()) { - type = errorType; - error(node, Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); - } - return (links.resolvedEnumType = type); - } - // Get type from reference to named type that cannot be generic (enum or type parameter) const res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { @@ -26409,6 +26399,7 @@ namespace ts { // A jsdoc typedef and callback are, by definition, type aliases case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: + case SyntaxKind.JSDocEnumTag: return DeclarationSpaces.ExportType; case SyntaxKind.ModuleDeclaration: return isAmbientModule(d as ModuleDeclaration) || getModuleInstanceState(d as ModuleDeclaration) !== ModuleInstanceState.NonInstantiated @@ -30325,6 +30316,7 @@ namespace ts { return checkJSDocAugmentsTag(node as JSDocAugmentsTag); case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: + case SyntaxKind.JSDocEnumTag: return checkJSDocTypeAliasTag(node as JSDocTypedefTag); case SyntaxKind.JSDocTemplateTag: return checkJSDocTemplateTag(node as JSDocTemplateTag); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 67c85147aed..099f7705f84 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2466,7 +2466,8 @@ namespace ts { kind: SyntaxKind.JSDocClassTag; } - export interface JSDocEnumTag extends JSDocTag { + export interface JSDocEnumTag extends JSDocTag, Declaration { + parent: JSDoc; kind: SyntaxKind.JSDocEnumTag; typeExpression?: JSDocTypeExpression; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index f3282d43723..d13e12a6f19 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2147,11 +2147,11 @@ namespace ts { return !!name && name.escapedText === "new"; } - export function isJSDocTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag { - return node.kind === SyntaxKind.JSDocTypedefTag || node.kind === SyntaxKind.JSDocCallbackTag; + export function isJSDocTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag { + return node.kind === SyntaxKind.JSDocTypedefTag || node.kind === SyntaxKind.JSDocCallbackTag || node.kind === SyntaxKind.JSDocEnumTag; } - export function isTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag | TypeAliasDeclaration { + export function isTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag | TypeAliasDeclaration { return isJSDocTypeAlias(node) || isTypeAliasDeclaration(node); } @@ -5091,7 +5091,7 @@ namespace ts { * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol * will be merged with) */ - function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined { + function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag): Identifier | undefined { const hostNode = declaration.parent.parent; if (!hostNode) { return undefined; @@ -5177,6 +5177,8 @@ namespace ts { } case SyntaxKind.JSDocTypedefTag: return getNameOfJSDocTypedef(declaration as JSDocTypedefTag); + case SyntaxKind.JSDocEnumTag: + return nameForNamelessJSDocTypedef(declaration as JSDocEnumTag); case SyntaxKind.ExportAssignment: { const { expression } = declaration as ExportAssignment; return isIdentifier(expression) ? expression : undefined; diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index b0b20c92e64..e8b4401b846 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -97,7 +97,7 @@ class TypeWriterWalker { if (!isSymbolWalk) { // Don't try to get the type of something that's already a type. // Exception for `T` in `type T = something` because that may evaluate to some interesting type. - if (ts.isPartOfTypeNode(node) || ts.isIdentifier(node) && !(ts.getMeaningFromDeclaration(node.parent) & ts.SemanticMeaning.Value) && !(ts.isTypeAlias(node.parent) && node.parent.name === node)) { + if (ts.isPartOfTypeNode(node) || ts.isIdentifier(node) && !(ts.getMeaningFromDeclaration(node.parent) & ts.SemanticMeaning.Value) && !(ts.isTypeAliasDeclaration(node.parent) && node.parent.name === node)) { return undefined; } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index c2bad61505b..6d81a6f08ab 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1589,7 +1589,8 @@ declare namespace ts { interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; } - interface JSDocEnumTag extends JSDocTag { + interface JSDocEnumTag extends JSDocTag, Declaration { + parent: JSDoc; kind: SyntaxKind.JSDocEnumTag; typeExpression?: JSDocTypeExpression; } diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 7a2559bbc22..ebd2d1471f7 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1589,7 +1589,8 @@ declare namespace ts { interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; } - interface JSDocEnumTag extends JSDocTag { + interface JSDocEnumTag extends JSDocTag, Declaration { + parent: JSDoc; kind: SyntaxKind.JSDocEnumTag; typeExpression?: JSDocTypeExpression; } diff --git a/tests/baselines/reference/enumTag.symbols b/tests/baselines/reference/enumTag.symbols index a54b9f4a3d8..87bcd6961a5 100644 --- a/tests/baselines/reference/enumTag.symbols +++ b/tests/baselines/reference/enumTag.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/jsdoc/a.js === /** @enum {string} */ const Target = { ->Target : Symbol(Target, Decl(a.js, 1, 5)) +>Target : Symbol(Target, Decl(a.js, 1, 5), Decl(a.js, 0, 4)) START: "start", >START : Symbol(START, Decl(a.js, 1, 16)) @@ -21,7 +21,7 @@ const Target = { } /** @enum number */ const Second = { ->Second : Symbol(Second, Decl(a.js, 10, 5)) +>Second : Symbol(Second, Decl(a.js, 10, 5), Decl(a.js, 9, 4)) MISTAKE: "end", >MISTAKE : Symbol(MISTAKE, Decl(a.js, 10, 16)) @@ -35,7 +35,7 @@ const Second = { } /** @enum {function(number): number} */ const Fs = { ->Fs : Symbol(Fs, Decl(a.js, 17, 5)) +>Fs : Symbol(Fs, Decl(a.js, 17, 5), Decl(a.js, 16, 4)) ADD1: n => n + 1, >ADD1 : Symbol(ADD1, Decl(a.js, 17, 12)) @@ -82,17 +82,17 @@ function consume(t,s,f) { var v = Target.START >v : Symbol(v, Decl(a.js, 35, 7)) >Target.START : Symbol(START, Decl(a.js, 1, 16)) ->Target : Symbol(Target, Decl(a.js, 1, 5)) +>Target : Symbol(Target, Decl(a.js, 1, 5), Decl(a.js, 0, 4)) >START : Symbol(START, Decl(a.js, 1, 16)) v = Target.UNKNOWN // error, can't find 'UNKNOWN' >v : Symbol(v, Decl(a.js, 35, 7)) ->Target : Symbol(Target, Decl(a.js, 1, 5)) +>Target : Symbol(Target, Decl(a.js, 1, 5), Decl(a.js, 0, 4)) v = Second.MISTAKE // meh..ok, I guess? >v : Symbol(v, Decl(a.js, 35, 7)) >Second.MISTAKE : Symbol(MISTAKE, Decl(a.js, 10, 16)) ->Second : Symbol(Second, Decl(a.js, 10, 5)) +>Second : Symbol(Second, Decl(a.js, 10, 5), Decl(a.js, 9, 4)) >MISTAKE : Symbol(MISTAKE, Decl(a.js, 10, 16)) v = 'something else' // allowed, like Typescript's classic enums and unlike its string enums @@ -105,14 +105,14 @@ function ff(s) { // element access with arbitrary string is an error only with noImplicitAny if (!Target[s]) { ->Target : Symbol(Target, Decl(a.js, 1, 5)) +>Target : Symbol(Target, Decl(a.js, 1, 5), Decl(a.js, 0, 4)) >s : Symbol(s, Decl(a.js, 41, 12)) return null } else { return Target[s] ->Target : Symbol(Target, Decl(a.js, 1, 5)) +>Target : Symbol(Target, Decl(a.js, 1, 5), Decl(a.js, 0, 4)) >s : Symbol(s, Decl(a.js, 41, 12)) } } diff --git a/tests/baselines/reference/enumTagCircularReference.errors.txt b/tests/baselines/reference/enumTagCircularReference.errors.txt index f876b5a33da..f42be3719f9 100644 --- a/tests/baselines/reference/enumTagCircularReference.errors.txt +++ b/tests/baselines/reference/enumTagCircularReference.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/jsdoc/bug27142.js(1,12): error TS2586: Enum type 'E' circularly references itself. +tests/cases/conformance/jsdoc/bug27142.js(1,5): error TS2456: Type alias 'E' circularly references itself. ==== tests/cases/conformance/jsdoc/bug27142.js (1 errors) ==== /** @enum {E} */ - ~ -!!! error TS2586: Enum type 'E' circularly references itself. + ~~~~~~~~~ +!!! error TS2456: Type alias 'E' circularly references itself. const E = { x: 0 }; \ No newline at end of file diff --git a/tests/baselines/reference/enumTagCircularReference.symbols b/tests/baselines/reference/enumTagCircularReference.symbols index e3c594ac9d1..1236c02e392 100644 --- a/tests/baselines/reference/enumTagCircularReference.symbols +++ b/tests/baselines/reference/enumTagCircularReference.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsdoc/bug27142.js === /** @enum {E} */ const E = { x: 0 }; ->E : Symbol(E, Decl(bug27142.js, 1, 5)) +>E : Symbol(E, Decl(bug27142.js, 1, 5), Decl(bug27142.js, 0, 4)) >x : Symbol(x, Decl(bug27142.js, 1, 11)) diff --git a/tests/baselines/reference/enumTagImported.symbols b/tests/baselines/reference/enumTagImported.symbols index ab9ab5eceb1..a79198aaae1 100644 --- a/tests/baselines/reference/enumTagImported.symbols +++ b/tests/baselines/reference/enumTagImported.symbols @@ -23,7 +23,7 @@ const tist = TestEnum.ADD === tests/cases/conformance/jsdoc/mod1.js === /** @enum {string} */ export const TestEnum = { ->TestEnum : Symbol(TestEnum, Decl(mod1.js, 1, 12)) +>TestEnum : Symbol(TestEnum, Decl(mod1.js, 1, 12), Decl(mod1.js, 0, 4)) ADD: 'add', >ADD : Symbol(ADD, Decl(mod1.js, 1, 25)) diff --git a/tests/baselines/reference/enumTagUseBeforeDefCrash.symbols b/tests/baselines/reference/enumTagUseBeforeDefCrash.symbols index 1cef96a9823..8ec8a90e64b 100644 --- a/tests/baselines/reference/enumTagUseBeforeDefCrash.symbols +++ b/tests/baselines/reference/enumTagUseBeforeDefCrash.symbols @@ -3,7 +3,7 @@ * @enum {number} */ var foo = { }; ->foo : Symbol(foo, Decl(bug27134.js, 3, 3)) +>foo : Symbol(foo, Decl(bug27134.js, 3, 3), Decl(bug27134.js, 1, 3)) /** * @type {foo} diff --git a/tests/baselines/reference/enumTagUseBeforeDefCrash.types b/tests/baselines/reference/enumTagUseBeforeDefCrash.types index 159781fee05..d9f800d0d03 100644 --- a/tests/baselines/reference/enumTagUseBeforeDefCrash.types +++ b/tests/baselines/reference/enumTagUseBeforeDefCrash.types @@ -3,7 +3,7 @@ * @enum {number} */ var foo = { }; ->foo : typeof foo +>foo : {} >{ } : {} /** diff --git a/tests/cases/fourslash/findAllRefs_jsEnum.ts b/tests/cases/fourslash/findAllRefs_jsEnum.ts index f9033d6c588..d492cd84de4 100644 --- a/tests/cases/fourslash/findAllRefs_jsEnum.ts +++ b/tests/cases/fourslash/findAllRefs_jsEnum.ts @@ -10,7 +10,7 @@ ////const e = [|E|].A; verify.singleReferenceGroup( -`enum E +`type E = string const E: { A: string; }`, "E"); diff --git a/tests/cases/fourslash/quickInfoJsdocEnum.ts b/tests/cases/fourslash/quickInfoJsdocEnum.ts index 9ef3b1edc78..b8264b52110 100644 --- a/tests/cases/fourslash/quickInfoJsdocEnum.ts +++ b/tests/cases/fourslash/quickInfoJsdocEnum.ts @@ -18,11 +18,10 @@ verify.noErrors(); verify.quickInfoAt("type", -`enum E`, +`type E = number`, "Doc"); verify.quickInfoAt("value", -`enum E -const E: { +`const E: { A: number; }`, "Doc"); From 3d09010dc8916446f3e7a00df7845bc982ae721f Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Fri, 26 Jul 2019 14:56:03 -0700 Subject: [PATCH 066/151] Intersect 'this' types in union signatures (#32538) * Intersect this types in union signatures * Actually update baselines --- src/compiler/checker.ts | 13 +- .../unionThisTypeInFunctions.errors.txt | 34 ++++ .../reference/unionThisTypeInFunctions.js | 4 +- .../unionThisTypeInFunctions.symbols | 2 +- .../reference/unionThisTypeInFunctions.types | 4 +- .../unionTypeCallSignatures5.errors.txt | 19 ++ .../reference/unionTypeCallSignatures5.types | 2 +- .../unionTypeCallSignatures6.errors.txt | 98 +++++++++ .../reference/unionTypeCallSignatures6.js | 69 +++++++ .../unionTypeCallSignatures6.symbols | 187 ++++++++++++++++++ .../reference/unionTypeCallSignatures6.types | 150 ++++++++++++++ .../thisType/unionThisTypeInFunctions.ts | 2 +- .../types/union/unionTypeCallSignatures6.ts | 55 ++++++ 13 files changed, 626 insertions(+), 13 deletions(-) create mode 100644 tests/baselines/reference/unionThisTypeInFunctions.errors.txt create mode 100644 tests/baselines/reference/unionTypeCallSignatures5.errors.txt create mode 100644 tests/baselines/reference/unionTypeCallSignatures6.errors.txt create mode 100644 tests/baselines/reference/unionTypeCallSignatures6.js create mode 100644 tests/baselines/reference/unionTypeCallSignatures6.symbols create mode 100644 tests/baselines/reference/unionTypeCallSignatures6.types create mode 100644 tests/cases/conformance/types/union/unionTypeCallSignatures6.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 834fb3eccfa..f8242ed6df7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7181,8 +7181,9 @@ namespace ts { } let result: Signature[] | undefined; for (let i = 0; i < signatureLists.length; i++) { - // Allow matching non-generic signatures to have excess parameters and different return types - const match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + // Allow matching non-generic signatures to have excess parameters and different return types. + // Prefer matching this types if possible. + const match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true); if (!match) { return undefined; } @@ -7205,7 +7206,7 @@ namespace ts { } for (const signature of signatureLists[i]) { // Only process signatures with parameter lists that aren't already in the result list - if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) { const unionSignatures = findMatchingSignatures(signatureLists, signature, i); if (unionSignatures) { let s = signature; @@ -7214,7 +7215,7 @@ namespace ts { let thisParameter = signature.thisParameter; const firstThisParameterOfUnionSignatures = forEach(unionSignatures, sig => sig.thisParameter); if (firstThisParameterOfUnionSignatures) { - const thisType = getUnionType(map(unionSignatures, sig => sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType), UnionReduction.Subtype); + const thisType = getIntersectionType(mapDefined(unionSignatures, sig => sig.thisParameter && getTypeOfSymbol(sig.thisParameter))); thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType); } s = createUnionSignature(signature, unionSignatures); @@ -7253,8 +7254,8 @@ namespace ts { } // A signature `this` type might be a read or a write position... It's very possible that it should be invariant // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be - // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does - const thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], UnionReduction.Subtype); + // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures. + const thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]); return createSymbolWithType(left, thisType); } diff --git a/tests/baselines/reference/unionThisTypeInFunctions.errors.txt b/tests/baselines/reference/unionThisTypeInFunctions.errors.txt new file mode 100644 index 00000000000..db03a5426fb --- /dev/null +++ b/tests/baselines/reference/unionThisTypeInFunctions.errors.txt @@ -0,0 +1,34 @@ +tests/cases/conformance/types/thisType/unionThisTypeInFunctions.ts(10,5): error TS2684: The 'this' context of type 'Real | Fake' is not assignable to method's 'this' of type 'Real & Fake'. + Type 'Real' is not assignable to type 'Real & Fake'. + Type 'Real' is not assignable to type 'Fake'. + Types of property 'method' are incompatible. + Type '(this: Real, n: number) => void' is not assignable to type '(this: Fake, n: number) => void'. + The 'this' types of each signature are incompatible. + Type 'Fake' is not assignable to type 'Real'. + Types of property 'data' are incompatible. + Type 'number' is not assignable to type 'string'. + + +==== tests/cases/conformance/types/thisType/unionThisTypeInFunctions.ts (1 errors) ==== + interface Real { + method(this: this, n: number): void; + data: string; + } + interface Fake { + method(this: this, n: number): void; + data: number; + } + function test(r: Real | Fake) { + r.method(12); // error + ~ +!!! error TS2684: The 'this' context of type 'Real | Fake' is not assignable to method's 'this' of type 'Real & Fake'. +!!! error TS2684: Type 'Real' is not assignable to type 'Real & Fake'. +!!! error TS2684: Type 'Real' is not assignable to type 'Fake'. +!!! error TS2684: Types of property 'method' are incompatible. +!!! error TS2684: Type '(this: Real, n: number) => void' is not assignable to type '(this: Fake, n: number) => void'. +!!! error TS2684: The 'this' types of each signature are incompatible. +!!! error TS2684: Type 'Fake' is not assignable to type 'Real'. +!!! error TS2684: Types of property 'data' are incompatible. +!!! error TS2684: Type 'number' is not assignable to type 'string'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/unionThisTypeInFunctions.js b/tests/baselines/reference/unionThisTypeInFunctions.js index 0d4b535ff8b..dca64b6d893 100644 --- a/tests/baselines/reference/unionThisTypeInFunctions.js +++ b/tests/baselines/reference/unionThisTypeInFunctions.js @@ -8,11 +8,11 @@ interface Fake { data: number; } function test(r: Real | Fake) { - r.method(12); + r.method(12); // error } //// [unionThisTypeInFunctions.js] function test(r) { - r.method(12); + r.method(12); // error } diff --git a/tests/baselines/reference/unionThisTypeInFunctions.symbols b/tests/baselines/reference/unionThisTypeInFunctions.symbols index eada1231750..b907519626a 100644 --- a/tests/baselines/reference/unionThisTypeInFunctions.symbols +++ b/tests/baselines/reference/unionThisTypeInFunctions.symbols @@ -27,7 +27,7 @@ function test(r: Real | Fake) { >Real : Symbol(Real, Decl(unionThisTypeInFunctions.ts, 0, 0)) >Fake : Symbol(Fake, Decl(unionThisTypeInFunctions.ts, 3, 1)) - r.method(12); + r.method(12); // error >r.method : Symbol(method, Decl(unionThisTypeInFunctions.ts, 0, 16), Decl(unionThisTypeInFunctions.ts, 4, 16)) >r : Symbol(r, Decl(unionThisTypeInFunctions.ts, 8, 14)) >method : Symbol(method, Decl(unionThisTypeInFunctions.ts, 0, 16), Decl(unionThisTypeInFunctions.ts, 4, 16)) diff --git a/tests/baselines/reference/unionThisTypeInFunctions.types b/tests/baselines/reference/unionThisTypeInFunctions.types index 44c03d73a61..af987759a55 100644 --- a/tests/baselines/reference/unionThisTypeInFunctions.types +++ b/tests/baselines/reference/unionThisTypeInFunctions.types @@ -21,8 +21,8 @@ function test(r: Real | Fake) { >test : (r: Real | Fake) => void >r : Real | Fake - r.method(12); ->r.method(12) : void + r.method(12); // error +>r.method(12) : any >r.method : ((this: Real, n: number) => void) | ((this: Fake, n: number) => void) >r : Real | Fake >method : ((this: Real, n: number) => void) | ((this: Fake, n: number) => void) diff --git a/tests/baselines/reference/unionTypeCallSignatures5.errors.txt b/tests/baselines/reference/unionTypeCallSignatures5.errors.txt new file mode 100644 index 00000000000..2dc6ebb002b --- /dev/null +++ b/tests/baselines/reference/unionTypeCallSignatures5.errors.txt @@ -0,0 +1,19 @@ +tests/cases/conformance/types/union/unionTypeCallSignatures5.ts(12,1): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'never'. + + +==== tests/cases/conformance/types/union/unionTypeCallSignatures5.ts (1 errors) ==== + // #31485 + interface A { + (this: void, b?: number): void; + } + interface B { + (this: number, b?: number): void; + } + interface C { + (i: number): void; + } + declare const fn: A | B | C; + fn(0); + ~~~~~ +!!! error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'never'. + \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures5.types b/tests/baselines/reference/unionTypeCallSignatures5.types index 53ce4ea6550..b9b5a6fbc0d 100644 --- a/tests/baselines/reference/unionTypeCallSignatures5.types +++ b/tests/baselines/reference/unionTypeCallSignatures5.types @@ -18,7 +18,7 @@ declare const fn: A | B | C; >fn : A | B | C fn(0); ->fn(0) : void +>fn(0) : any >fn : A | B | C >0 : 0 diff --git a/tests/baselines/reference/unionTypeCallSignatures6.errors.txt b/tests/baselines/reference/unionTypeCallSignatures6.errors.txt new file mode 100644 index 00000000000..51b18b204a7 --- /dev/null +++ b/tests/baselines/reference/unionTypeCallSignatures6.errors.txt @@ -0,0 +1,98 @@ +tests/cases/conformance/types/union/unionTypeCallSignatures6.ts(11,1): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B'. + Type 'void' is not assignable to type 'A'. +tests/cases/conformance/types/union/unionTypeCallSignatures6.ts(13,1): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A'. +tests/cases/conformance/types/union/unionTypeCallSignatures6.ts(38,4): error TS2349: This expression is not callable. + Each member of the union type 'F3 | F4' has signatures, but none of those signatures are compatible with each other. +tests/cases/conformance/types/union/unionTypeCallSignatures6.ts(39,1): error TS2684: The 'this' context of type 'A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; }' is not assignable to method's 'this' of type 'B'. + Property 'b' is missing in type 'A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; }' but required in type 'B'. +tests/cases/conformance/types/union/unionTypeCallSignatures6.ts(48,1): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B'. + Type 'void' is not assignable to type 'A'. +tests/cases/conformance/types/union/unionTypeCallSignatures6.ts(55,1): error TS2769: No overload matches this call. + Overload 1 of 2, '(this: A & B & C): void', gave the following error. + The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B & C'. + Type 'void' is not assignable to type 'A'. + Overload 2 of 2, '(this: A & B): void', gave the following error. + The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B'. + Type 'void' is not assignable to type 'A'. + + +==== tests/cases/conformance/types/union/unionTypeCallSignatures6.ts (6 errors) ==== + type A = { a: string }; + type B = { b: number }; + type C = { c: string }; + type D = { d: number }; + type F0 = () => void; + + // #31547 + type F1 = (this: A) => void; + type F2 = (this: B) => void; + declare var f1: F1 | F2; + f1(); // error + ~~~~ +!!! error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B'. +!!! error TS2684: Type 'void' is not assignable to type 'A'. + declare var f2: F0 | F1; + f2(); // error + ~~~~ +!!! error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A'. + + interface F3 { + (this: A): void; + (this: B): void; + } + interface F4 { + (this: C): void; + (this: D): void; + } + interface F5 { + (this: C): void; + (this: B): void; + } + + declare var x1: A & C & { + f0: F0 | F3; + f1: F1 | F3; + f2: F1 | F4; + f3: F3 | F4; + f4: F3 | F5; + } + x1.f0(); + x1.f1(); + x1.f2(); + x1.f3(); // error + ~~ +!!! error TS2349: This expression is not callable. +!!! error TS2349: Each member of the union type 'F3 | F4' has signatures, but none of those signatures are compatible with each other. + x1.f4(); // error + ~~ +!!! error TS2684: The 'this' context of type 'A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; }' is not assignable to method's 'this' of type 'B'. +!!! error TS2684: Property 'b' is missing in type 'A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; }' but required in type 'B'. +!!! related TS2728 tests/cases/conformance/types/union/unionTypeCallSignatures6.ts:2:12: 'b' is declared here. + + declare var x2: A & B & { + f4: F3 | F5; + } + x2.f4(); + + type F6 = (this: A & B) => void; + declare var f3: F1 | F6; + f3(); // error + ~~~~ +!!! error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B'. +!!! error TS2684: Type 'void' is not assignable to type 'A'. + + interface F7 { + (this: A & B & C): void; + (this: A & B): void; + } + declare var f4: F6 | F7; + f4(); // error + ~~~~ +!!! error TS2769: No overload matches this call. +!!! error TS2769: Overload 1 of 2, '(this: A & B & C): void', gave the following error. +!!! error TS2769: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B & C'. +!!! error TS2769: Type 'void' is not assignable to type 'A'. +!!! error TS2769: Overload 2 of 2, '(this: A & B): void', gave the following error. +!!! error TS2769: The 'this' context of type 'void' is not assignable to method's 'this' of type 'A & B'. +!!! error TS2769: Type 'void' is not assignable to type 'A'. + \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures6.js b/tests/baselines/reference/unionTypeCallSignatures6.js new file mode 100644 index 00000000000..32e0518cbb8 --- /dev/null +++ b/tests/baselines/reference/unionTypeCallSignatures6.js @@ -0,0 +1,69 @@ +//// [unionTypeCallSignatures6.ts] +type A = { a: string }; +type B = { b: number }; +type C = { c: string }; +type D = { d: number }; +type F0 = () => void; + +// #31547 +type F1 = (this: A) => void; +type F2 = (this: B) => void; +declare var f1: F1 | F2; +f1(); // error +declare var f2: F0 | F1; +f2(); // error + +interface F3 { + (this: A): void; + (this: B): void; +} +interface F4 { + (this: C): void; + (this: D): void; +} +interface F5 { + (this: C): void; + (this: B): void; +} + +declare var x1: A & C & { + f0: F0 | F3; + f1: F1 | F3; + f2: F1 | F4; + f3: F3 | F4; + f4: F3 | F5; +} +x1.f0(); +x1.f1(); +x1.f2(); +x1.f3(); // error +x1.f4(); // error + +declare var x2: A & B & { + f4: F3 | F5; +} +x2.f4(); + +type F6 = (this: A & B) => void; +declare var f3: F1 | F6; +f3(); // error + +interface F7 { + (this: A & B & C): void; + (this: A & B): void; +} +declare var f4: F6 | F7; +f4(); // error + + +//// [unionTypeCallSignatures6.js] +f1(); // error +f2(); // error +x1.f0(); +x1.f1(); +x1.f2(); +x1.f3(); // error +x1.f4(); // error +x2.f4(); +f3(); // error +f4(); // error diff --git a/tests/baselines/reference/unionTypeCallSignatures6.symbols b/tests/baselines/reference/unionTypeCallSignatures6.symbols new file mode 100644 index 00000000000..87d1928f069 --- /dev/null +++ b/tests/baselines/reference/unionTypeCallSignatures6.symbols @@ -0,0 +1,187 @@ +=== tests/cases/conformance/types/union/unionTypeCallSignatures6.ts === +type A = { a: string }; +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) +>a : Symbol(a, Decl(unionTypeCallSignatures6.ts, 0, 10)) + +type B = { b: number }; +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) +>b : Symbol(b, Decl(unionTypeCallSignatures6.ts, 1, 10)) + +type C = { c: string }; +>C : Symbol(C, Decl(unionTypeCallSignatures6.ts, 1, 23)) +>c : Symbol(c, Decl(unionTypeCallSignatures6.ts, 2, 10)) + +type D = { d: number }; +>D : Symbol(D, Decl(unionTypeCallSignatures6.ts, 2, 23)) +>d : Symbol(d, Decl(unionTypeCallSignatures6.ts, 3, 10)) + +type F0 = () => void; +>F0 : Symbol(F0, Decl(unionTypeCallSignatures6.ts, 3, 23)) + +// #31547 +type F1 = (this: A) => void; +>F1 : Symbol(F1, Decl(unionTypeCallSignatures6.ts, 4, 21)) +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 7, 11)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) + +type F2 = (this: B) => void; +>F2 : Symbol(F2, Decl(unionTypeCallSignatures6.ts, 7, 28)) +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 8, 11)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) + +declare var f1: F1 | F2; +>f1 : Symbol(f1, Decl(unionTypeCallSignatures6.ts, 9, 11)) +>F1 : Symbol(F1, Decl(unionTypeCallSignatures6.ts, 4, 21)) +>F2 : Symbol(F2, Decl(unionTypeCallSignatures6.ts, 7, 28)) + +f1(); // error +>f1 : Symbol(f1, Decl(unionTypeCallSignatures6.ts, 9, 11)) + +declare var f2: F0 | F1; +>f2 : Symbol(f2, Decl(unionTypeCallSignatures6.ts, 11, 11)) +>F0 : Symbol(F0, Decl(unionTypeCallSignatures6.ts, 3, 23)) +>F1 : Symbol(F1, Decl(unionTypeCallSignatures6.ts, 4, 21)) + +f2(); // error +>f2 : Symbol(f2, Decl(unionTypeCallSignatures6.ts, 11, 11)) + +interface F3 { +>F3 : Symbol(F3, Decl(unionTypeCallSignatures6.ts, 12, 5)) + + (this: A): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 15, 3)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) + + (this: B): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 16, 3)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) +} +interface F4 { +>F4 : Symbol(F4, Decl(unionTypeCallSignatures6.ts, 17, 1)) + + (this: C): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 19, 3)) +>C : Symbol(C, Decl(unionTypeCallSignatures6.ts, 1, 23)) + + (this: D): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 20, 3)) +>D : Symbol(D, Decl(unionTypeCallSignatures6.ts, 2, 23)) +} +interface F5 { +>F5 : Symbol(F5, Decl(unionTypeCallSignatures6.ts, 21, 1)) + + (this: C): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 23, 3)) +>C : Symbol(C, Decl(unionTypeCallSignatures6.ts, 1, 23)) + + (this: B): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 24, 3)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) +} + +declare var x1: A & C & { +>x1 : Symbol(x1, Decl(unionTypeCallSignatures6.ts, 27, 11)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) +>C : Symbol(C, Decl(unionTypeCallSignatures6.ts, 1, 23)) + + f0: F0 | F3; +>f0 : Symbol(f0, Decl(unionTypeCallSignatures6.ts, 27, 25)) +>F0 : Symbol(F0, Decl(unionTypeCallSignatures6.ts, 3, 23)) +>F3 : Symbol(F3, Decl(unionTypeCallSignatures6.ts, 12, 5)) + + f1: F1 | F3; +>f1 : Symbol(f1, Decl(unionTypeCallSignatures6.ts, 28, 14)) +>F1 : Symbol(F1, Decl(unionTypeCallSignatures6.ts, 4, 21)) +>F3 : Symbol(F3, Decl(unionTypeCallSignatures6.ts, 12, 5)) + + f2: F1 | F4; +>f2 : Symbol(f2, Decl(unionTypeCallSignatures6.ts, 29, 14)) +>F1 : Symbol(F1, Decl(unionTypeCallSignatures6.ts, 4, 21)) +>F4 : Symbol(F4, Decl(unionTypeCallSignatures6.ts, 17, 1)) + + f3: F3 | F4; +>f3 : Symbol(f3, Decl(unionTypeCallSignatures6.ts, 30, 14)) +>F3 : Symbol(F3, Decl(unionTypeCallSignatures6.ts, 12, 5)) +>F4 : Symbol(F4, Decl(unionTypeCallSignatures6.ts, 17, 1)) + + f4: F3 | F5; +>f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 31, 14)) +>F3 : Symbol(F3, Decl(unionTypeCallSignatures6.ts, 12, 5)) +>F5 : Symbol(F5, Decl(unionTypeCallSignatures6.ts, 21, 1)) +} +x1.f0(); +>x1.f0 : Symbol(f0, Decl(unionTypeCallSignatures6.ts, 27, 25)) +>x1 : Symbol(x1, Decl(unionTypeCallSignatures6.ts, 27, 11)) +>f0 : Symbol(f0, Decl(unionTypeCallSignatures6.ts, 27, 25)) + +x1.f1(); +>x1.f1 : Symbol(f1, Decl(unionTypeCallSignatures6.ts, 28, 14)) +>x1 : Symbol(x1, Decl(unionTypeCallSignatures6.ts, 27, 11)) +>f1 : Symbol(f1, Decl(unionTypeCallSignatures6.ts, 28, 14)) + +x1.f2(); +>x1.f2 : Symbol(f2, Decl(unionTypeCallSignatures6.ts, 29, 14)) +>x1 : Symbol(x1, Decl(unionTypeCallSignatures6.ts, 27, 11)) +>f2 : Symbol(f2, Decl(unionTypeCallSignatures6.ts, 29, 14)) + +x1.f3(); // error +>x1.f3 : Symbol(f3, Decl(unionTypeCallSignatures6.ts, 30, 14)) +>x1 : Symbol(x1, Decl(unionTypeCallSignatures6.ts, 27, 11)) +>f3 : Symbol(f3, Decl(unionTypeCallSignatures6.ts, 30, 14)) + +x1.f4(); // error +>x1.f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 31, 14)) +>x1 : Symbol(x1, Decl(unionTypeCallSignatures6.ts, 27, 11)) +>f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 31, 14)) + +declare var x2: A & B & { +>x2 : Symbol(x2, Decl(unionTypeCallSignatures6.ts, 40, 11)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) + + f4: F3 | F5; +>f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 40, 25)) +>F3 : Symbol(F3, Decl(unionTypeCallSignatures6.ts, 12, 5)) +>F5 : Symbol(F5, Decl(unionTypeCallSignatures6.ts, 21, 1)) +} +x2.f4(); +>x2.f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 40, 25)) +>x2 : Symbol(x2, Decl(unionTypeCallSignatures6.ts, 40, 11)) +>f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 40, 25)) + +type F6 = (this: A & B) => void; +>F6 : Symbol(F6, Decl(unionTypeCallSignatures6.ts, 43, 8)) +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 45, 11)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) + +declare var f3: F1 | F6; +>f3 : Symbol(f3, Decl(unionTypeCallSignatures6.ts, 46, 11)) +>F1 : Symbol(F1, Decl(unionTypeCallSignatures6.ts, 4, 21)) +>F6 : Symbol(F6, Decl(unionTypeCallSignatures6.ts, 43, 8)) + +f3(); // error +>f3 : Symbol(f3, Decl(unionTypeCallSignatures6.ts, 46, 11)) + +interface F7 { +>F7 : Symbol(F7, Decl(unionTypeCallSignatures6.ts, 47, 5)) + + (this: A & B & C): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 50, 3)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) +>C : Symbol(C, Decl(unionTypeCallSignatures6.ts, 1, 23)) + + (this: A & B): void; +>this : Symbol(this, Decl(unionTypeCallSignatures6.ts, 51, 3)) +>A : Symbol(A, Decl(unionTypeCallSignatures6.ts, 0, 0)) +>B : Symbol(B, Decl(unionTypeCallSignatures6.ts, 0, 23)) +} +declare var f4: F6 | F7; +>f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 53, 11)) +>F6 : Symbol(F6, Decl(unionTypeCallSignatures6.ts, 43, 8)) +>F7 : Symbol(F7, Decl(unionTypeCallSignatures6.ts, 47, 5)) + +f4(); // error +>f4 : Symbol(f4, Decl(unionTypeCallSignatures6.ts, 53, 11)) + diff --git a/tests/baselines/reference/unionTypeCallSignatures6.types b/tests/baselines/reference/unionTypeCallSignatures6.types new file mode 100644 index 00000000000..930c91b1109 --- /dev/null +++ b/tests/baselines/reference/unionTypeCallSignatures6.types @@ -0,0 +1,150 @@ +=== tests/cases/conformance/types/union/unionTypeCallSignatures6.ts === +type A = { a: string }; +>A : A +>a : string + +type B = { b: number }; +>B : B +>b : number + +type C = { c: string }; +>C : C +>c : string + +type D = { d: number }; +>D : D +>d : number + +type F0 = () => void; +>F0 : F0 + +// #31547 +type F1 = (this: A) => void; +>F1 : F1 +>this : A + +type F2 = (this: B) => void; +>F2 : F2 +>this : B + +declare var f1: F1 | F2; +>f1 : F1 | F2 + +f1(); // error +>f1() : any +>f1 : F1 | F2 + +declare var f2: F0 | F1; +>f2 : F1 | F0 + +f2(); // error +>f2() : any +>f2 : F1 | F0 + +interface F3 { + (this: A): void; +>this : A + + (this: B): void; +>this : B +} +interface F4 { + (this: C): void; +>this : C + + (this: D): void; +>this : D +} +interface F5 { + (this: C): void; +>this : C + + (this: B): void; +>this : B +} + +declare var x1: A & C & { +>x1 : A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; } + + f0: F0 | F3; +>f0 : F0 | F3 + + f1: F1 | F3; +>f1 : F1 | F3 + + f2: F1 | F4; +>f2 : F1 | F4 + + f3: F3 | F4; +>f3 : F3 | F4 + + f4: F3 | F5; +>f4 : F3 | F5 +} +x1.f0(); +>x1.f0() : void +>x1.f0 : F0 | F3 +>x1 : A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; } +>f0 : F0 | F3 + +x1.f1(); +>x1.f1() : void +>x1.f1 : F1 | F3 +>x1 : A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; } +>f1 : F1 | F3 + +x1.f2(); +>x1.f2() : void +>x1.f2 : F1 | F4 +>x1 : A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; } +>f2 : F1 | F4 + +x1.f3(); // error +>x1.f3() : any +>x1.f3 : F3 | F4 +>x1 : A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; } +>f3 : F3 | F4 + +x1.f4(); // error +>x1.f4() : any +>x1.f4 : F3 | F5 +>x1 : A & C & { f0: F0 | F3; f1: F1 | F3; f2: F1 | F4; f3: F3 | F4; f4: F3 | F5; } +>f4 : F3 | F5 + +declare var x2: A & B & { +>x2 : A & B & { f4: F3 | F5; } + + f4: F3 | F5; +>f4 : F3 | F5 +} +x2.f4(); +>x2.f4() : void +>x2.f4 : F3 | F5 +>x2 : A & B & { f4: F3 | F5; } +>f4 : F3 | F5 + +type F6 = (this: A & B) => void; +>F6 : F6 +>this : A & B + +declare var f3: F1 | F6; +>f3 : F1 | F6 + +f3(); // error +>f3() : any +>f3 : F1 | F6 + +interface F7 { + (this: A & B & C): void; +>this : A & B & C + + (this: A & B): void; +>this : A & B +} +declare var f4: F6 | F7; +>f4 : F6 | F7 + +f4(); // error +>f4() : any +>f4 : F6 | F7 + diff --git a/tests/cases/conformance/types/thisType/unionThisTypeInFunctions.ts b/tests/cases/conformance/types/thisType/unionThisTypeInFunctions.ts index 4f74058cc48..a35019d372e 100644 --- a/tests/cases/conformance/types/thisType/unionThisTypeInFunctions.ts +++ b/tests/cases/conformance/types/thisType/unionThisTypeInFunctions.ts @@ -7,5 +7,5 @@ interface Fake { data: number; } function test(r: Real | Fake) { - r.method(12); + r.method(12); // error } diff --git a/tests/cases/conformance/types/union/unionTypeCallSignatures6.ts b/tests/cases/conformance/types/union/unionTypeCallSignatures6.ts new file mode 100644 index 00000000000..0fe98847205 --- /dev/null +++ b/tests/cases/conformance/types/union/unionTypeCallSignatures6.ts @@ -0,0 +1,55 @@ +type A = { a: string }; +type B = { b: number }; +type C = { c: string }; +type D = { d: number }; +type F0 = () => void; + +// #31547 +type F1 = (this: A) => void; +type F2 = (this: B) => void; +declare var f1: F1 | F2; +f1(); // error +declare var f2: F0 | F1; +f2(); // error + +interface F3 { + (this: A): void; + (this: B): void; +} +interface F4 { + (this: C): void; + (this: D): void; +} +interface F5 { + (this: C): void; + (this: B): void; +} + +declare var x1: A & C & { + f0: F0 | F3; + f1: F1 | F3; + f2: F1 | F4; + f3: F3 | F4; + f4: F3 | F5; +} +x1.f0(); +x1.f1(); +x1.f2(); +x1.f3(); // error +x1.f4(); // error + +declare var x2: A & B & { + f4: F3 | F5; +} +x2.f4(); + +type F6 = (this: A & B) => void; +declare var f3: F1 | F6; +f3(); // error + +interface F7 { + (this: A & B & C): void; + (this: A & B): void; +} +declare var f4: F6 | F7; +f4(); // error From a9e0a7766e30eff61f76ca85b380e65f45c8eb12 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 27 Jul 2019 08:50:26 -0700 Subject: [PATCH 067/151] Record full inference status in visitation cache --- src/compiler/checker.ts | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a69751673f6..27c8a027cbc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15462,7 +15462,7 @@ namespace ts { let visited: Map; let bivariant = false; let propagationType: Type; - let inferenceCount = 0; + let inferenceMatch = false; let inferenceIncomplete = false; let allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); @@ -15576,7 +15576,7 @@ namespace ts { clearCachedInferences(inferences); } } - inferenceCount++; + inferenceMatch = true; return; } else { @@ -15668,15 +15668,21 @@ namespace ts { function invokeOnce(source: Type, target: Type, action: (source: Type, target: Type) => void) { const key = source.id + "," + target.id; - const count = visited && visited.get(key); - if (count !== undefined) { - inferenceCount += count; + const status = visited && visited.get(key); + if (status !== undefined) { + if (status & 1) inferenceMatch = true; + if (status & 2) inferenceIncomplete = true; return; } (visited || (visited = createMap())).set(key, 0); - const startCount = inferenceCount; + const saveInferenceMatch = inferenceMatch; + const saveInferenceIncomplete = inferenceIncomplete; + inferenceMatch = false; + inferenceIncomplete = false; action(source, target); - visited.set(key, inferenceCount - startCount); + visited.set(key, (inferenceMatch ? 1 : 0) | (inferenceIncomplete ? 2 : 0)); + inferenceMatch = inferenceMatch || saveInferenceMatch; + inferenceIncomplete = inferenceIncomplete || saveInferenceIncomplete; } function inferFromMatchingType(source: Type, targets: Type[], matches: (s: Type, t: Type) => boolean) { @@ -15759,9 +15765,11 @@ namespace ts { } else { for (let i = 0; i < sources.length; i++) { - const count = inferenceCount; + const saveInferenceMatch = inferenceMatch; + inferenceMatch = false; inferFromTypes(sources[i], t); - if (count !== inferenceCount) matched[i] = true; + if (inferenceMatch) matched[i] = true; + inferenceMatch = inferenceMatch || saveInferenceMatch; } } } From 58ff76abf663190a91ada6e3f23e9b3fed417af0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 28 Jul 2019 09:01:11 -0700 Subject: [PATCH 068/151] Properly instantiate contextual type for object literal methods --- src/compiler/checker.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f8242ed6df7..1ad92eebc21 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19099,10 +19099,13 @@ namespace ts { // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. - function getApparentTypeOfContextualType(node: Expression, contextFlags?: ContextFlags): Type | undefined { - const contextualType = instantiateContextualType(getContextualType(node, contextFlags), node, contextFlags); - if (contextualType) { - const apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true); + function getApparentTypeOfContextualType(node: Expression | MethodDeclaration, contextFlags?: ContextFlags): Type | undefined { + const contextualType = isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node, contextFlags) : + getContextualType(node, contextFlags); + const instantiatedType = instantiateContextualType(contextualType, node, contextFlags); + if (instantiatedType) { + const apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); if (apparentType.flags & TypeFlags.Union) { if (isObjectLiteralExpression(node)) { return discriminateContextualTypeByObjectMembers(node, apparentType as UnionType); @@ -19426,9 +19429,7 @@ namespace ts { if (typeTagSignature) { return typeTagSignature; } - const type = isObjectLiteralMethod(node) ? - getContextualTypeForObjectLiteralMethod(node, ContextFlags.Signature) : - getApparentTypeOfContextualType(node, ContextFlags.Signature); + const type = getApparentTypeOfContextualType(node, ContextFlags.Signature); if (!type) { return undefined; } From a717d3ab44b2cacc9e0fb36861bbe7c428bba6fc Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 28 Jul 2019 09:05:57 -0700 Subject: [PATCH 069/151] Add regression test --- tests/cases/compiler/instantiateContextualTypes.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/cases/compiler/instantiateContextualTypes.ts b/tests/cases/compiler/instantiateContextualTypes.ts index 3165011ecff..4059bd5202e 100644 --- a/tests/cases/compiler/instantiateContextualTypes.ts +++ b/tests/cases/compiler/instantiateContextualTypes.ts @@ -174,3 +174,13 @@ class Interesting { declare function invoke(f: () => T): T; let xx: 0 | 1 | 2 = invoke(() => 1); + +// Repro from #32416 + +declare function assignPartial(target: T, partial: Partial): T; + +let obj = { + foo(bar: string) {} +} + +assignPartial(obj, { foo(...args) {} }); // args has type [string] From 4a17581f67a0c0cd413adcd7ce0e0ffe30698122 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 28 Jul 2019 09:06:04 -0700 Subject: [PATCH 070/151] Accept new baselines --- .../reference/instantiateContextualTypes.js | 14 ++++++++++ .../instantiateContextualTypes.symbols | 26 +++++++++++++++++++ .../instantiateContextualTypes.types | 24 +++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/tests/baselines/reference/instantiateContextualTypes.js b/tests/baselines/reference/instantiateContextualTypes.js index 9de6bfb612c..46d87cb1153 100644 --- a/tests/baselines/reference/instantiateContextualTypes.js +++ b/tests/baselines/reference/instantiateContextualTypes.js @@ -172,6 +172,16 @@ class Interesting { declare function invoke(f: () => T): T; let xx: 0 | 1 | 2 = invoke(() => 1); + +// Repro from #32416 + +declare function assignPartial(target: T, partial: Partial): T; + +let obj = { + foo(bar: string) {} +} + +assignPartial(obj, { foo(...args) {} }); // args has type [string] //// [instantiateContextualTypes.js] @@ -222,3 +232,7 @@ class Interesting { } } let xx = invoke(() => 1); +let obj = { + foo(bar) { } +}; +assignPartial(obj, { foo(...args) { } }); // args has type [string] diff --git a/tests/baselines/reference/instantiateContextualTypes.symbols b/tests/baselines/reference/instantiateContextualTypes.symbols index 1250edd585b..d3e8a7a317c 100644 --- a/tests/baselines/reference/instantiateContextualTypes.symbols +++ b/tests/baselines/reference/instantiateContextualTypes.symbols @@ -481,3 +481,29 @@ let xx: 0 | 1 | 2 = invoke(() => 1); >xx : Symbol(xx, Decl(instantiateContextualTypes.ts, 172, 3)) >invoke : Symbol(invoke, Decl(instantiateContextualTypes.ts, 166, 1)) +// Repro from #32416 + +declare function assignPartial(target: T, partial: Partial): T; +>assignPartial : Symbol(assignPartial, Decl(instantiateContextualTypes.ts, 172, 36)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 176, 31)) +>target : Symbol(target, Decl(instantiateContextualTypes.ts, 176, 34)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 176, 31)) +>partial : Symbol(partial, Decl(instantiateContextualTypes.ts, 176, 44)) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 176, 31)) +>T : Symbol(T, Decl(instantiateContextualTypes.ts, 176, 31)) + +let obj = { +>obj : Symbol(obj, Decl(instantiateContextualTypes.ts, 178, 3)) + + foo(bar: string) {} +>foo : Symbol(foo, Decl(instantiateContextualTypes.ts, 178, 11)) +>bar : Symbol(bar, Decl(instantiateContextualTypes.ts, 179, 6)) +} + +assignPartial(obj, { foo(...args) {} }); // args has type [string] +>assignPartial : Symbol(assignPartial, Decl(instantiateContextualTypes.ts, 172, 36)) +>obj : Symbol(obj, Decl(instantiateContextualTypes.ts, 178, 3)) +>foo : Symbol(foo, Decl(instantiateContextualTypes.ts, 182, 20)) +>args : Symbol(args, Decl(instantiateContextualTypes.ts, 182, 25)) + diff --git a/tests/baselines/reference/instantiateContextualTypes.types b/tests/baselines/reference/instantiateContextualTypes.types index 88e6ca7e4dd..b5317b6f756 100644 --- a/tests/baselines/reference/instantiateContextualTypes.types +++ b/tests/baselines/reference/instantiateContextualTypes.types @@ -422,3 +422,27 @@ let xx: 0 | 1 | 2 = invoke(() => 1); >() => 1 : () => 1 >1 : 1 +// Repro from #32416 + +declare function assignPartial(target: T, partial: Partial): T; +>assignPartial : (target: T, partial: Partial) => T +>target : T +>partial : Partial + +let obj = { +>obj : { foo(bar: string): void; } +>{ foo(bar: string) {}} : { foo(bar: string): void; } + + foo(bar: string) {} +>foo : (bar: string) => void +>bar : string +} + +assignPartial(obj, { foo(...args) {} }); // args has type [string] +>assignPartial(obj, { foo(...args) {} }) : { foo(bar: string): void; } +>assignPartial : (target: T, partial: Partial) => T +>obj : { foo(bar: string): void; } +>{ foo(...args) {} } : { foo(bar: string): void; } +>foo : (bar: string) => void +>args : [string] + From 30aad9db8dc6fe09fe4e21fe973e984c35c201dc Mon Sep 17 00:00:00 2001 From: Orta Therox Date: Mon, 29 Jul 2019 09:46:42 -0400 Subject: [PATCH 071/151] Support more terminators for parsing jsdoc filepaths --- src/compiler/parser.ts | 12 ++++++----- src/compiler/scanner.ts | 2 +- src/harness/fourslash.ts | 4 ++++ src/services/classifier.ts | 1 + .../fourslash/jsDocDontBreakWithNamespaces.ts | 20 ++++++++++++++++--- 5 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 9762302b7a2..b585adb04ac 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2428,17 +2428,19 @@ namespace ts { function parseJSDocType(): TypeNode { scanner.setInJSDocType(true); - const dotdotdot = parseOptionalToken(SyntaxKind.DotDotDotToken); const moduleSpecifier = parseOptionalToken(SyntaxKind.ModuleKeyword); - let type = parseTypeOrTypePredicate(); - scanner.setInJSDocType(false); if (moduleSpecifier) { const moduleTag = createNode(SyntaxKind.JSDocNamepathType, moduleSpecifier.pos) as JSDocNamepathType; - while (token() !== SyntaxKind.CloseBraceToken && token() !== SyntaxKind.EndOfFileToken) { + const terminators = [SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, SyntaxKind.CommaToken, SyntaxKind.CloseParenToken]; + while (terminators.indexOf(token()) < 0) { nextTokenJSDoc(); } - type = finishNode(moduleTag); + return finishNode(moduleTag); } + + const dotdotdot = parseOptionalToken(SyntaxKind.DotDotDotToken); + let type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { const variadic = createNode(SyntaxKind.JSDocVariadicType, dotdotdot.pos) as JSDocVariadicType; variadic.type = type; diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index f949893171a..3109da91788 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1983,7 +1983,7 @@ namespace ts { // First non-whitespace character on this line. let firstNonWhitespace = 0; // These initial values are special because the first line is: - // firstNonWhitespace = 0 to indicate that we want leading whitspace, + // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { char = text.charCodeAt(pos); diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index f12506be2fb..b59f4e15dc4 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1268,6 +1268,10 @@ namespace FourSlash { private verifySignatureHelpWorker(options: FourSlashInterface.VerifySignatureHelpOptions) { const help = this.getSignatureHelp({ triggerReason: options.triggerReason })!; + if (!help) { + this.raiseError("Could not get a help signature"); + } + const selectedItem = help.items[help.selectedItemIndex]; // Argument index may exceed number of parameters const currentParameter = selectedItem.parameters[help.argumentIndex] as ts.SignatureHelpParameter | undefined; diff --git a/src/services/classifier.ts b/src/services/classifier.ts index f85a69681de..5da0354dc13 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -1,4 +1,5 @@ namespace ts { + /** The classifier is used for syntactic highlighting in editors via the TSServer */ export function createClassifier(): Classifier { const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false); diff --git a/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts b/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts index 7807d5d30d1..5be2f3e7b62 100644 --- a/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts +++ b/tests/cases/fourslash/jsDocDontBreakWithNamespaces.ts @@ -5,13 +5,27 @@ //// * @returns {module:@nodefuel/web~Webserver~wsServer#hello} Websocket server object //// */ ////function foo() { } -////foo(''/**/); +////foo(''/*foo*/); +//// +/////** +//// * @type {module:xxxxx} */ +//// */ +////function bar() { } +////bar(''/*bar*/); + verify.signatureHelp({ - marker: "", + marker: "foo", text: "foo(): any", docComment: "", tags: [ - { name: "returns", text: "Websocket server object" }, + { name: "returns", text: "Websocket server object" }, ], }); + +verify.signatureHelp({ + marker: "bar", + text: "bar(): void", + docComment: "", + tags: [], +}); From b963e1a2a7e3b1056ee2552927fa08fcc51e4c7d Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 29 Jul 2019 10:33:43 -0700 Subject: [PATCH 072/151] Update LKG (#32578) * Update LKG * Add @types/node version bump * Small paatches/casts to be compatible with latest node * Accept API baseline update * Make internal NodeBuffer compatable with latest Buffer * Why do we even have an internal buffer type * Sync up internal buffer type better * Fix lint * Readd mroe missing Buffer methods --- lib/enu/diagnosticMessages.generated.json.lcg | 424 +- lib/it/diagnosticMessages.generated.json | 4 +- lib/ja/diagnosticMessages.generated.json | 4 +- lib/ko/diagnosticMessages.generated.json | 140 +- lib/lib.dom.d.ts | 4022 ++- lib/lib.dom.iterable.d.ts | 111 +- lib/lib.es2015.collection.d.ts | 2 +- lib/lib.es2015.core.d.ts | 18 +- lib/lib.es2015.generator.d.ts | 10 +- lib/lib.es2015.iterable.d.ts | 26 +- lib/lib.es2015.promise.d.ts | 70 +- lib/lib.es2018.asyncgenerator.d.ts | 79 + lib/lib.es2018.asynciterable.d.ts | 9 +- lib/lib.es2018.d.ts | 1 + lib/lib.es2019.d.ts | 1 + lib/lib.es2019.object.d.ts | 35 + lib/lib.es2019.string.d.ts | 4 +- lib/lib.es2020.d.ts | 23 + lib/lib.es2020.full.d.ts | 25 + lib/lib.es2020.string.d.ts | 30 + lib/lib.es2020.symbol.wellknown.d.ts | 39 + lib/lib.es5.d.ts | 81 +- lib/lib.esnext.bigint.d.ts | 8 +- lib/lib.webworker.d.ts | 2245 +- lib/pl/diagnosticMessages.generated.json | 4 +- lib/protocol.d.ts | 57 +- lib/ru/diagnosticMessages.generated.json | 4 +- lib/tsc.js | 20474 ++++++----- lib/tsserver.js | 30143 +++++++++------- lib/tsserverlibrary.d.ts | 861 +- lib/tsserverlibrary.js | 30124 ++++++++------- lib/typescript.d.ts | 793 +- lib/typescript.js | 29662 ++++++++------- lib/typescriptServices.d.ts | 793 +- lib/typescriptServices.js | 29662 ++++++++------- lib/typingsInstaller.js | 23362 ++++++------ lib/zh-cn/diagnosticMessages.generated.json | 2 +- package.json | 2 +- src/compiler/sys.ts | 114 +- src/harness/harness.ts | 2 +- src/testRunner/externalCompileRunner.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 1124 +- tests/baselines/reference/api/typescript.d.ts | 1055 +- 43 files changed, 100855 insertions(+), 74796 deletions(-) create mode 100644 lib/lib.es2018.asyncgenerator.d.ts create mode 100644 lib/lib.es2019.object.d.ts create mode 100644 lib/lib.es2020.d.ts create mode 100644 lib/lib.es2020.full.d.ts create mode 100644 lib/lib.es2020.string.d.ts create mode 100644 lib/lib.es2020.symbol.wellknown.d.ts diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 0b66fd7760c..77e5d6f2236 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -141,9 +141,9 @@ - + - + @@ -189,12 +189,6 @@ - - - - - - @@ -675,12 +669,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -849,6 +867,12 @@ + + + + + + @@ -867,6 +891,12 @@ + + + + + + @@ -1209,6 +1239,12 @@ + + + + + + @@ -1413,18 +1449,18 @@ - - - - - - + + + + + + @@ -1593,12 +1629,6 @@ - - - - - - @@ -1617,6 +1647,24 @@ + + + + + + + + + + + + + + + + + + @@ -1683,12 +1731,6 @@ - - - - - - @@ -1863,6 +1905,12 @@ + + + + + + @@ -2037,6 +2085,12 @@ + + + + + + @@ -2061,12 +2115,6 @@ - - - - - - @@ -2151,6 +2199,12 @@ + + + + + + @@ -2187,6 +2241,12 @@ + + + + + + {1}'?]]> @@ -2199,6 +2259,12 @@ + + + + + + @@ -2421,6 +2487,24 @@ + + + + + + + + + + + + + + + + + + @@ -2433,6 +2517,12 @@ + + + + + + @@ -2663,7 +2753,7 @@ - + @@ -2811,6 +2901,24 @@ + + + + + + + + + + + + + + + + + + @@ -2865,9 +2973,9 @@ - + - + @@ -2925,6 +3033,12 @@ + + + + + + @@ -2955,12 +3069,6 @@ - - - - - - @@ -3033,18 +3141,6 @@ - - - - - - - - - - - - @@ -3063,9 +3159,9 @@ - + - + @@ -3333,6 +3429,12 @@ + + + + + + @@ -3597,6 +3699,12 @@ + + + + + + @@ -3795,6 +3903,12 @@ + + + + + + @@ -3891,6 +4005,12 @@ + + + + + + @@ -3945,6 +4065,24 @@ + + + + + + + + + + + + + + + + + + @@ -3963,6 +4101,18 @@ + + + + + + + + + + + + @@ -3987,6 +4137,18 @@ + + + + + + + + + + + + @@ -4173,6 +4335,12 @@ + + + + + + @@ -4233,6 +4401,12 @@ + + + + + + @@ -4503,6 +4677,12 @@ + + + + + + @@ -4587,12 +4767,6 @@ - - - - - - @@ -4911,6 +5085,12 @@ + + + + + + @@ -4959,6 +5139,12 @@ + + + + + + @@ -5601,6 +5787,18 @@ + + + + + + + + + + + + @@ -5679,6 +5877,12 @@ + + + + + + @@ -5715,6 +5919,18 @@ + + + + + + + + + + + + @@ -5889,6 +6105,12 @@ + + + + + + @@ -5901,15 +6123,15 @@ - + - + - + - + @@ -5955,6 +6177,18 @@ + + + + + + + + + + + + @@ -5967,6 +6201,12 @@ + + + + + + @@ -5991,6 +6231,12 @@ + + + + + + @@ -6045,6 +6291,18 @@ + + + + + + + + + + + + @@ -6375,6 +6633,12 @@ + + + + + + @@ -6717,6 +6981,12 @@ + + + + + + @@ -6891,6 +7161,12 @@ + + + + + + @@ -6915,6 +7191,12 @@ + + + + + + @@ -7137,6 +7419,12 @@ + + + + + + @@ -7227,6 +7515,12 @@ + + + + + + diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index 9f8ef7d48f4..51981810ba2 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -355,7 +355,7 @@ "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'elemento contiene implicitamente un tipo 'any' perché al tipo '{0}' non è assegnata alcuna firma dell'indice.", "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Crea un BOM (Byte Order Mark) UTF-8 all'inizio dei file di output.", "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping di origine invece di file separati.", - "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente alle mappe di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente ai mapping di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.", "Enable_project_compilation_6302": "Abilitare la compilazione dei progetti", "Enable_strict_checking_of_function_types_6186": "Abilita il controllo tassativo dei tipi funzione.", @@ -445,7 +445,7 @@ "Function_overload_must_be_static_2387": "L'overload della funzione deve essere statico.", "Function_overload_must_not_be_static_2388": "L'overload della funzione non deve essere statico.", "Generate_get_and_set_accessors_95046": "Generare le funzioni di accesso 'get' e 'set'", - "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Genera un sourcemap per ogni file '.d.ts' corrispondente.", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "Genera un mapping di origine per ogni file '.d.ts' corrispondente.", "Generates_corresponding_d_ts_file_6002": "Genera il file '.d.ts' corrispondente.", "Generates_corresponding_map_file_6043": "Genera il file '.map' corrispondente.", "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "Il tipo del generatore è implicitamente '{0}' perché non contiene alcun valore. Provare a specificare un tipo restituito.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 6877a89c753..d3029982ca6 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -355,7 +355,7 @@ "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "型 '{0}' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。", "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "出力ファイルの最初に UTF-8 バイト順マーク(BOM) を生成します。", "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", - "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", + "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内でソースマップと共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", "Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。", "Enable_project_compilation_6302": "プロジェクトのコンパイルを有効にします", "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", @@ -445,7 +445,7 @@ "Function_overload_must_be_static_2387": "関数のオーバーロードは静的でなければなりません。", "Function_overload_must_not_be_static_2388": "関数のオーバーロードは静的にはできせん。", "Generate_get_and_set_accessors_95046": "'get' および 'set' アクセサーの生成", - "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "対応する各 '.d.ts' ファイルに sourcemap を生成します。", + "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000": "対応する各 '.d.ts' ファイルにソースマップを生成します。", "Generates_corresponding_d_ts_file_6002": "対応する '.d.ts' ファイルを生成します。", "Generates_corresponding_map_file_6043": "対応する '.map' ファイルを生成します。", "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025": "ジェネレーターは値を生成しないため、暗黙的に型 '{0}' になります。戻り値の型を指定することを検討してください。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index a1b1320115a..abda4ace91f 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -309,7 +309,7 @@ "Declare_static_property_0_90027": "'{0}' 정적 속성 선언", "Decorators_are_not_valid_here_1206": "데코레이터는 여기에 사용할 수 없습니다.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "동일한 이름의 여러 get/set 접근자에 데코레이터를 적용할 수 없습니다.", - "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Delete_all_unused_declarations_95024": "사용하지 않는 선언 모두 삭제", "Delete_the_outputs_of_all_projects_6365": "모든 프로젝트의 출력 삭제", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[사용되지 않음] 대신 '--jsxFactory'를 사용합니다. 'react' JSX 내보내기를 대상으로 할 경우 createElement에 대해 호출되는 개체를 지정합니다.", @@ -395,10 +395,10 @@ "Export_declarations_are_not_permitted_in_a_namespace_1194": "네임스페이스에서는 내보내기 선언이 허용되지 않습니다.", "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "내보낸 외부 패키지 입력 항목 파일 '{0}'은(는) 모듈이 아닙니다. 패키지 작성자에게 문의하여 패키지 정의를 업데이트하세요.", "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "내보낸 외부 패키지 입력 항목 파일에는 삼중 슬래시 참조가 포함될 수 없습니다. 패키지 작성자에게 문의하여 패키지 정의를 업데이트하세요.", - "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "내보낸 형식 별칭 '{0}'은(는) '{1}' 전용 이름을 포함하거나 사용 중입니다.", + "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "내보낸 형식 별칭 '{0}'은(는) '{1}' 프라이빗 이름을 포함하거나 사용 중입니다.", "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "내보낸 변수 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "내보낸 변수 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Exported_variable_0_has_or_is_using_private_name_1_4025": "내보낸 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "내보낸 변수 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "내보낸 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "내보내기 및 내보내기 할당는 모듈 확대에서 허용되지 않습니다.", "Expression_expected_1109": "식이 필요합니다.", "Expression_or_comma_expected_1137": "식 또는 쉼표가 필요합니다.", @@ -471,10 +471,10 @@ "Implement_all_unimplemented_interfaces_95032": "구현되지 않은 인터페이스 모두 구현", "Implement_inherited_abstract_class_90007": "상속된 추상 클래스 구현", "Implement_interface_0_90006": "'{0}' 인터페이스 구현", - "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "내보낸 클래스 '{0}'의 Implements 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "내보낸 클래스 '{0}'의 Implements 절이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Import_0_from_module_1_90013": "\"{1}\" 모듈에서 '{0}' 가져오기", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript 모듈을 대상으로 하는 경우 할당 가져오기를 사용할 수 없습니다. 대신 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' 또는 다른 모듈 형식 사용을 고려하세요.", - "Import_declaration_0_is_using_private_name_1_4000": "가져오기 선언 '{0}'이(가) 전용 이름 '{1}'을(를) 사용하고 있습니다.", + "Import_declaration_0_is_using_private_name_1_4000": "가져오기 선언 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 사용하고 있습니다.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "가져오기 선언이 '{0}'의 로컬 선언과 충돌합니다.", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "네임스페이스의 가져오기 선언은 모듈을 참조할 수 없습니다.", "Import_emit_helpers_from_tslib_6139": "'tslib'에서 내보내기 도우미를 가져오세요.", @@ -563,8 +563,8 @@ "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "병합된 선언 '{0}'에는 기본 내보내기 선언을 포함할 수 없습니다. 대신 별도의 'export default {0}' 선언을 추가하세요.", "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "메타 속성 '{0}'은(는) 함수 선언, 함수 식 또는 생성기의 본문에서만 사용할 수 있습니다.", "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "'{0}' 메서드는 abstract로 표시되어 있으므로 구현이 있을 수 없습니다.", - "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "내보낸 인터페이스의 '{0}' 메서드가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "내보낸 인터페이스의 '{0}' 메서드가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "내보낸 인터페이스의 '{0}' 메서드가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "내보낸 인터페이스의 '{0}' 메서드가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Modifiers_cannot_appear_here_1184": "한정자를 여기에 표시할 수 없습니다.", "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "모듈 '{0}'은(는) 형식을 참조하지 않지만, 여기에서 형식으로 사용됩니다.", "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "모듈 '{0}'은(는) 값을 참조하지 않지만, 여기에서 값으로 사용됩니다.", @@ -639,36 +639,36 @@ "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "오버로드 시그니처는 모두 내보내거나 모두 내보내지 않아야 합니다.", "Overload_signatures_must_all_be_optional_or_required_2386": "오버로드 시그니처는 모두 선택 사항이거나 필수 사항이어야 합니다.", - "Overload_signatures_must_all_be_public_private_or_protected_2385": "오버로드 시그니처는 모두 공용, 전용 또는 보호된 상태여야 합니다.", + "Overload_signatures_must_all_be_public_private_or_protected_2385": "오버로드 시그니처는 모두 퍼블릭, 프라이빗 또는 보호된 상태여야 합니다.", "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "매개 변수 '{0}'은(는) 해당 이니셜라이저에서 참조할 수 없습니다.", "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' 매개 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' 매개 변수는 '{1}' 매개 변수와 같은 위치에 있지 않습니다.", - "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "내보낸 인터페이스에 있는 호출 시그니처의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "내보낸 클래스에 있는 생성자의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "내보낸 인터페이스에 있는 생성자 시그니처의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "내보낸 함수의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "내보낸 함수의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "내보낸 함수의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "내보낸 함수의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "내보낸 함수의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "내보낸 인터페이스에 있는 인덱스 시그니처의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "내보낸 인터페이스에 있는 메서드의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "내보낸 클래스에 있는 공용 메서드의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "내보낸 클래스에 있는 공용 정적 메서드의 '{0}' 매개 변수가 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parameter_cannot_have_question_mark_and_initializer_1015": "매개 변수에 물음표와 이니셜라이저를 사용할 수 없습니다.", "Parameter_declaration_expected_1138": "매개 변수 선언이 필요합니다.", - "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "내보낸 클래스에 있는 공용 setter '{0}'의 매개 변수 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "strict 모드에서 구문 분석하고 각 소스 파일에 대해 \"use strict\"를 내보냅니다.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' 패턴에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", "Prefix_0_with_an_underscore_90025": "'{0}' 앞에 밑줄 추가", @@ -709,9 +709,9 @@ "Property_0_is_protected_in_type_1_but_public_in_type_2_2444": "'{0}' 속성은 '{1}' 형식에서는 보호된 속성이지만 '{2}' 형식에서는 공용입니다.", "Property_0_is_used_before_being_assigned_2565": "'{0}' 속성이 할당되기 전에 사용되었습니다.", "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX 분배 특성의 '{0}' 속성을 대상 속성에 할당할 수 없습니다.", - "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "내보낸 클래스 식의 속성 '{0}'이(가) 비공개가 아니거나 보호되지 않을 수 있습니다.", - "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "내보낸 인터페이스의 '{0}' 속성이 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "내보낸 인터페이스의 '{0}' 속성이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "내보낸 클래스 식의 속성 '{0}'이(가) 프라이빗이 아니거나 보호되지 않을 수 있습니다.", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "내보낸 인터페이스의 '{0}' 속성이 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "내보낸 인터페이스의 '{0}' 속성이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "'{1}' 형식의 '{0}' 속성을 숫자 인덱스 형식 '{2}'에 할당할 수 없습니다.", "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "'{1}' 형식의 '{0}' 속성을 문자열 인덱스 형식 '{2}'에 할당할 수 없습니다.", "Property_assignment_expected_1136": "속성 할당이 필요합니다.", @@ -720,17 +720,17 @@ "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "속성 값은 문자열 리터럴, 숫자 리터럴, 'true', 'false', 'null', 개체 리터럴 또는 배열 리터럴이어야 합니다.", "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'ES5' 또는 'ES3'을 대상으로 할 경우 'for-of', spread 및 소멸의 반복 가능한 개체를 완벽히 지원합니다.", "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "내보낸 클래스의 공용 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "내보낸 클래스의 공용 메서드 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "내보낸 클래스의 공용 메서드의 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "내보낸 클래스의 공용 메서드 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "내보낸 클래스의 공용 메서드의 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "내보낸 클래스의 공용 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "내보낸 클래스의 공용 속성 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "내보낸 클래스의 공용 속성 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "내보낸 클래스의 공용 속성 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "내보낸 클래스의 공용 속성 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "내보낸 클래스에 있는 공용 정적 메서드 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "내보낸 클래스에 있는 공용 정적 메서드 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "내보낸 클래스의 공용 정적 메서드 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "내보낸 클래스에 있는 공용 정적 속성 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", - "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 프라이빗 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "내보낸 클래스의 공용 정적 속성 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", @@ -765,30 +765,30 @@ "Resolving_with_primary_search_path_0_6121": "기본 검색 경로 '{0}'을(를) 사용하여 확인하는 중입니다.", "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest 매개 변수 '{0}'에는 암시적으로 'any[]' 형식이 포함됩니다.", "Rest_types_may_only_be_created_from_object_types_2700": "rest 유형은 개체 형식에서만 만들 수 있습니다.", - "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", - "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "내보낸 인터페이스에 있는 호출 시그니처의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "내보낸 인터페이스에 있는 생성자 시그니처의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "생성자 시그니처의 반환 형식을 클래스의 인스턴스 형식에 할당할 수 있어야 합니다.", "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "내보낸 함수의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "내보낸 함수의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "내보낸 함수의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", - "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", - "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "내보낸 인터페이스에 있는 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "내보낸 인터페이스에 있는 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "내보낸 함수의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "내보낸 함수의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "내보낸 인터페이스에 있는 인덱스 시그니처의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "내보낸 인터페이스에 있는 메서드의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "내보낸 인터페이스에 있는 메서드의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "내보낸 클래스에 있는 공용 getter '{0}'의 반환 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "내보낸 클래스에 있는 공용 메서드의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 외부 모듈 {2}의 이름 '{1}'을(를) 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 전용 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 프라이빗 모듈 '{2}'의 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "내보낸 클래스에 있는 공용 정적 getter '{0}'의 반환 형식이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 외부 모듈 {1}의 '{0}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", - "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", - "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 프라이빗 모듈 '{1}'의 '{0}' 이름을 가지고 있거나 사용 중입니다.", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "이전 프로그램에서 변경되지 않았으므로 '{0}'에서 발생하는 모듈 확인을 다시 사용합니다.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "'{0}' 모듈 확인을 이전 프로그램의 '{1}' 파일에 다시 사용합니다.", "Rewrite_all_as_indexed_access_types_95034": "인덱싱된 액세스 형식으로 모두 다시 작성", @@ -939,15 +939,15 @@ "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", "Type_parameter_0_has_a_circular_default_2716": "형식 매개 변수 '{0}'에 순환 기본값이 있습니다.", - "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "내보낸 인터페이스에 있는 생성자 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "내보낸 클래스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "내보낸 함수의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "내보낸 인터페이스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "내보낸 형식 별칭의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "내보낸 인터페이스에 있는 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "내보낸 클래스에 있는 공용 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "내보낸 클래스에 있는 공용 정적 메서드의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "내보낸 인터페이스에 있는 생성자 시그니처의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "내보낸 클래스의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "내보낸 함수의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "내보낸 인터페이스의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "내보낸 형식 별칭의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "내보낸 인터페이스에 있는 메서드의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "내보낸 클래스에 있는 공용 메서드의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "내보낸 클래스에 있는 공용 정적 메서드의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Type_parameter_declaration_expected_1139": "형식 매개 변수 선언이 필요합니다.", "Type_parameter_list_cannot_be_empty_1098": "형식 매개 변수 목록은 비워 둘 수 없습니다.", "Type_parameter_name_cannot_be_0_2368": "형식 매개 변수 이름은 '{0}'일 수 없습니다.", @@ -955,7 +955,7 @@ "Type_predicate_0_is_not_assignable_to_1_1226": "형식 조건자 '{0}'을(를) '{1}'에 할당할 수 없습니다.", "Type_reference_directive_0_was_not_resolved_6120": "======== 형식 참조 지시문 '{0}'이(가) 확인되지 않았습니다. ========", "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119": "======== 형식 참조 지시문 '{0}'이(가) '{1}'(으)로 확인되었습니다. 주: {2}. ========", - "Types_have_separate_declarations_of_a_private_property_0_2442": "형식에 별도의 전용 속성 '{0}' 선언이 있습니다.", + "Types_have_separate_declarations_of_a_private_property_0_2442": "형식에 별도의 프라이빗 속성 '{0}' 선언이 있습니다.", "Types_of_parameters_0_and_1_are_incompatible_2328": "'{0}' 및 '{1}' 매개 변수의 형식이 호환되지 않습니다.", "Types_of_property_0_are_incompatible_2326": "'{0}' 속성의 형식이 호환되지 않습니다.", "Unable_to_open_file_0_6050": "'{0}' 파일을 열 수 없습니다.", @@ -1047,8 +1047,8 @@ "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "앰비언트 모듈 및 모듈 확대는 항상 표시되므로 'export' 한정자를 적용할 수 없습니다.", "extends_clause_already_seen_1172": "'extends' 절이 이미 있습니다.", "extends_clause_must_precede_implements_clause_1173": "'extends' 절은 'implements' 절 앞에 와야 합니다.", - "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "내보낸 클래스 '{0}'의 Extends 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "내보낸 인터페이스 '{0}'의 Extends 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "내보낸 클래스 '{0}'의 Extends 절이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "내보낸 인터페이스 '{0}'의 Extends 절이 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "file_6025": "파일", "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' 및 'set' 접근자는 동일한 'this' 형식이어야 합니다.", "get_and_set_accessor_must_have_the_same_type_2380": "'get' 및 'set' 접근자의 형식이 같아야 합니다.", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 7817a0e4267..92500ffc046 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -153,6 +153,34 @@ interface AudioWorkletNodeOptions extends AudioNodeOptions { processorOptions?: any; } +interface AuthenticationExtensionsClientInputs { + appid?: string; + authnSel?: AuthenticatorSelectionList; + exts?: boolean; + loc?: boolean; + txAuthGeneric?: txAuthGenericArg; + txAuthSimple?: string; + uvi?: boolean; + uvm?: boolean; +} + +interface AuthenticationExtensionsClientOutputs { + appid?: boolean; + authnSel?: boolean; + exts?: AuthenticationExtensionsSupported; + loc?: Coordinates; + txAuthGeneric?: ArrayBuffer; + txAuthSimple?: string; + uvi?: ArrayBuffer; + uvm?: UvmEntries; +} + +interface AuthenticatorSelectionCriteria { + authenticatorAttachment?: AuthenticatorAttachment; + requireResidentKey?: boolean; + userVerification?: UserVerificationRequirement; +} + interface BiquadFilterOptions extends AudioNodeOptions { Q?: number; detune?: number; @@ -171,7 +199,6 @@ interface ByteLengthChunk { } interface CacheQueryOptions { - cacheName?: string; ignoreMethod?: boolean; ignoreSearch?: boolean; ignoreVary?: boolean; @@ -179,6 +206,7 @@ interface CacheQueryOptions { interface CanvasRenderingContext2DSettings { alpha?: boolean; + desynchronized?: boolean; } interface ChannelMergerOptions extends AudioNodeOptions { @@ -256,7 +284,7 @@ interface ConstrainDoubleRange extends DoubleRange { ideal?: number; } -interface ConstrainLongRange extends LongRange { +interface ConstrainULongRange extends ULongRange { exact?: number; ideal?: number; } @@ -271,6 +299,17 @@ interface ConvolverOptions extends AudioNodeOptions { disableNormalization?: boolean; } +interface CredentialCreationOptions { + publicKey?: PublicKeyCredentialCreationOptions; + signal?: AbortSignal; +} + +interface CredentialRequestOptions { + mediation?: CredentialMediationRequirement; + publicKey?: PublicKeyCredentialRequestOptions; + signal?: AbortSignal; +} + interface CustomEventInit extends EventInit { detail?: T; } @@ -330,21 +369,27 @@ interface DelayOptions extends AudioNodeOptions { maxDelayTime?: number; } -interface DeviceAccelerationDict { +interface DeviceLightEventInit extends EventInit { + value?: number; +} + +interface DeviceMotionEventAccelerationInit { x?: number | null; y?: number | null; z?: number | null; } -interface DeviceLightEventInit extends EventInit { - value?: number; +interface DeviceMotionEventInit extends EventInit { + acceleration?: DeviceMotionEventAccelerationInit; + accelerationIncludingGravity?: DeviceMotionEventAccelerationInit; + interval?: number; + rotationRate?: DeviceMotionEventRotationRateInit; } -interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict | null; - accelerationIncludingGravity?: DeviceAccelerationDict | null; - interval?: number | null; - rotationRate?: DeviceRotationRateDict | null; +interface DeviceMotionEventRotationRateInit { + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceOrientationEventInit extends EventInit { @@ -354,10 +399,9 @@ interface DeviceOrientationEventInit extends EventInit { gamma?: number | null; } -interface DeviceRotationRateDict { - alpha?: number | null; - beta?: number | null; - gamma?: number | null; +interface DevicePermissionDescriptor extends PermissionDescriptor { + deviceId?: string; + name: "camera" | "microphone" | "speaker"; } interface DocumentTimelineOptions { @@ -412,6 +456,10 @@ interface EffectTiming { iterations?: number; } +interface ElementCreationOptions { + is?: string; +} + interface ElementDefinitionOptions { extends?: string; } @@ -444,7 +492,6 @@ interface EventModifierInit extends UIEventInit { modifierFnLock?: boolean; modifierHyper?: boolean; modifierNumLock?: boolean; - modifierOS?: boolean; modifierScrollLock?: boolean; modifierSuper?: boolean; modifierSymbol?: boolean; @@ -553,11 +600,27 @@ interface IIRFilterOptions extends AudioNodeOptions { feedforward: number[]; } +interface ImageBitmapRenderingContextSettings { + alpha?: boolean; +} + +interface ImageEncodeOptions { + quality?: number; + type?: string; +} + +interface InputEventInit extends UIEventInit { + data?: string | null; + inputType?: string; + isComposing?: boolean; +} + interface IntersectionObserverEntryInit { boundingClientRect: DOMRectInit; + intersectionRatio: number; intersectionRect: DOMRectInit; isIntersecting: boolean; - rootBounds: DOMRectInit; + rootBounds: DOMRectInit | null; target: Element; time: number; } @@ -595,6 +658,7 @@ interface KeyAlgorithm { interface KeyboardEventInit extends EventModifierInit { code?: string; + isComposing?: boolean; key?: string; location?: number; repeat?: boolean; @@ -616,11 +680,6 @@ interface KeyframeEffectOptions extends EffectTiming { iterationComposite?: IterationCompositeOperation; } -interface LongRange { - max?: number; - min?: number; -} - interface MediaElementAudioSourceOptions { mediaElement: HTMLMediaElement; } @@ -678,39 +737,43 @@ interface MediaStreamTrackAudioSourceOptions { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack | null; + track: MediaStreamTrack; } interface MediaTrackCapabilities { - aspectRatio?: number | DoubleRange; + aspectRatio?: DoubleRange; + autoGainControl?: boolean[]; + channelCount?: ULongRange; deviceId?: string; echoCancellation?: boolean[]; - facingMode?: string; - frameRate?: number | DoubleRange; + facingMode?: string[]; + frameRate?: DoubleRange; groupId?: string; - height?: number | LongRange; - sampleRate?: number | LongRange; - sampleSize?: number | LongRange; - volume?: number | DoubleRange; - width?: number | LongRange; + height?: ULongRange; + latency?: DoubleRange; + noiseSuppression?: boolean[]; + resizeMode?: string[]; + sampleRate?: ULongRange; + sampleSize?: ULongRange; + width?: ULongRange; } interface MediaTrackConstraintSet { - aspectRatio?: number | ConstrainDoubleRange; - channelCount?: number | ConstrainLongRange; - deviceId?: string | string[] | ConstrainDOMStringParameters; - displaySurface?: string | string[] | ConstrainDOMStringParameters; - echoCancellation?: boolean | ConstrainBooleanParameters; - facingMode?: string | string[] | ConstrainDOMStringParameters; - frameRate?: number | ConstrainDoubleRange; - groupId?: string | string[] | ConstrainDOMStringParameters; - height?: number | ConstrainLongRange; - latency?: number | ConstrainDoubleRange; - logicalSurface?: boolean | ConstrainBooleanParameters; - sampleRate?: number | ConstrainLongRange; - sampleSize?: number | ConstrainLongRange; - volume?: number | ConstrainDoubleRange; - width?: number | ConstrainLongRange; + aspectRatio?: ConstrainDouble; + autoGainControl?: ConstrainBoolean; + channelCount?: ConstrainULong; + deviceId?: ConstrainDOMString; + echoCancellation?: ConstrainBoolean; + facingMode?: ConstrainDOMString; + frameRate?: ConstrainDouble; + groupId?: ConstrainDOMString; + height?: ConstrainULong; + latency?: ConstrainDouble; + noiseSuppression?: ConstrainBoolean; + resizeMode?: ConstrainDOMString; + sampleRate?: ConstrainULong; + sampleSize?: ConstrainULong; + width?: ConstrainULong; } interface MediaTrackConstraints extends MediaTrackConstraintSet { @@ -719,29 +782,37 @@ interface MediaTrackConstraints extends MediaTrackConstraintSet { interface MediaTrackSettings { aspectRatio?: number; + autoGainControl?: boolean; + channelCount?: number; deviceId?: string; echoCancellation?: boolean; facingMode?: string; frameRate?: number; groupId?: string; height?: number; + latency?: number; + noiseSuppression?: boolean; + resizeMode?: string; sampleRate?: number; sampleSize?: number; - volume?: number; width?: number; } interface MediaTrackSupportedConstraints { aspectRatio?: boolean; + autoGainControl?: boolean; + channelCount?: boolean; deviceId?: boolean; echoCancellation?: boolean; facingMode?: boolean; frameRate?: boolean; groupId?: boolean; height?: boolean; + latency?: boolean; + noiseSuppression?: boolean; + resizeMode?: boolean; sampleRate?: boolean; sampleSize?: boolean; - volume?: boolean; width?: boolean; } @@ -753,6 +824,11 @@ interface MessageEventInit extends EventInit { source?: MessageEventSource | null; } +interface MidiPermissionDescriptor extends PermissionDescriptor { + name: "midi"; + sysex?: boolean; +} + interface MouseEventInit extends EventModifierInit { button?: number; buttons?: number; @@ -765,13 +841,38 @@ interface MouseEventInit extends EventModifierInit { screenY?: number; } +interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string; +} + interface MutationObserverInit { + /** + * Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed and attributes is true or omitted. + */ attributeFilter?: string[]; + /** + * Set to true if attributes is true or omitted and target's attribute value before the mutation needs to be recorded. + */ attributeOldValue?: boolean; + /** + * Set to true if mutations to target's attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is specified. + */ attributes?: boolean; + /** + * Set to true if mutations to target's data are to be observed. Can be omitted if characterDataOldValue is specified. + */ characterData?: boolean; + /** + * Set to true if characterData is set to true or omitted and target's data before the mutation needs to be recorded. + */ characterDataOldValue?: boolean; + /** + * Set to true if mutations to target's children are to be observed. + */ childList?: boolean; + /** + * Set to true if mutations to not just target, but also target's descendants are to be observed. + */ subtree?: boolean; } @@ -914,7 +1015,8 @@ interface Pbkdf2Params extends Algorithm { interface PerformanceObserverInit { buffered?: boolean; - entryTypes: string[]; + entryTypes?: string[]; + type?: string; } interface PeriodicWaveConstraints { @@ -926,10 +1028,15 @@ interface PeriodicWaveOptions extends PeriodicWaveConstraints { real?: number[] | Float32Array; } +interface PermissionDescriptor { + name: PermissionName; +} + interface PipeOptions { preventAbort?: boolean; preventCancel?: boolean; preventClose?: boolean; + signal?: AbortSignal; } interface PointerEventInit extends MouseEventInit { @@ -955,6 +1062,10 @@ interface PositionOptions { timeout?: number; } +interface PostMessageOptions { + transfer?: any[]; +} + interface ProgressEventInit extends EventInit { lengthComputable?: boolean; loaded?: number; @@ -973,6 +1084,57 @@ interface PropertyIndexedKeyframes { [property: string]: string | string[] | number | null | (number | null)[] | undefined; } +interface PublicKeyCredentialCreationOptions { + attestation?: AttestationConveyancePreference; + authenticatorSelection?: AuthenticatorSelectionCriteria; + challenge: BufferSource; + excludeCredentials?: PublicKeyCredentialDescriptor[]; + extensions?: AuthenticationExtensionsClientInputs; + pubKeyCredParams: PublicKeyCredentialParameters[]; + rp: PublicKeyCredentialRpEntity; + timeout?: number; + user: PublicKeyCredentialUserEntity; +} + +interface PublicKeyCredentialDescriptor { + id: BufferSource; + transports?: AuthenticatorTransport[]; + type: PublicKeyCredentialType; +} + +interface PublicKeyCredentialEntity { + icon?: string; + name: string; +} + +interface PublicKeyCredentialParameters { + alg: COSEAlgorithmIdentifier; + type: PublicKeyCredentialType; +} + +interface PublicKeyCredentialRequestOptions { + allowCredentials?: PublicKeyCredentialDescriptor[]; + challenge: BufferSource; + extensions?: AuthenticationExtensionsClientInputs; + rpId?: string; + timeout?: number; + userVerification?: UserVerificationRequirement; +} + +interface PublicKeyCredentialRpEntity extends PublicKeyCredentialEntity { + id?: string; +} + +interface PublicKeyCredentialUserEntity extends PublicKeyCredentialEntity { + displayName: string; + id: BufferSource; +} + +interface PushPermissionDescriptor extends PermissionDescriptor { + name: "push"; + userVisibleOnly?: boolean; +} + interface PushSubscriptionJSON { endpoint?: string; expirationTime?: number | null; @@ -1361,18 +1523,57 @@ interface RegistrationOptions { } interface RequestInit { + /** + * A BodyInit object or null to set request's body. + */ body?: BodyInit | null; + /** + * A string indicating how the request will interact with the browser's cache to set request's cache. + */ cache?: RequestCache; + /** + * A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. + */ credentials?: RequestCredentials; + /** + * A Headers object, an object literal, or an array of two-item arrays to set request's headers. + */ headers?: HeadersInit; + /** + * A cryptographic hash of the resource to be fetched by request. Sets request's integrity. + */ integrity?: string; + /** + * A boolean to set request's keepalive. + */ keepalive?: boolean; + /** + * A string to set request's method. + */ method?: string; + /** + * A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. + */ mode?: RequestMode; + /** + * A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. + */ redirect?: RequestRedirect; + /** + * A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. + */ referrer?: string; + /** + * A referrer policy to set request's referrerPolicy. + */ referrerPolicy?: ReferrerPolicy; + /** + * An AbortSignal to set request's signal. + */ signal?: AbortSignal | null; + /** + * Can only be null. Used to disassociate request from any Window. + */ window?: any; } @@ -1519,6 +1720,11 @@ interface TextDecoderOptions { ignoreBOM?: boolean; } +interface TextEncoderEncodeIntoResult { + read?: number; + written?: number; +} + interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; targetTouches?: Touch[]; @@ -1566,6 +1772,11 @@ interface UIEventInit extends EventInit { view?: Window | null; } +interface ULongRange { + max?: number; + min?: number; +} + interface UnderlyingByteSource { autoAllocateChunkSize?: number; cancel?: ReadableStreamErrorCallback; @@ -1615,14 +1826,15 @@ interface WebAuthnExtensions { } interface WebGLContextAttributes { - alpha?: GLboolean; - antialias?: GLboolean; - depth?: GLboolean; + alpha?: boolean; + antialias?: boolean; + depth?: boolean; + desynchronized?: boolean; failIfMajorPerformanceCaveat?: boolean; powerPreference?: WebGLPowerPreference; - premultipliedAlpha?: GLboolean; - preserveDrawingBuffer?: GLboolean; - stencil?: GLboolean; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; + stencil?: boolean; } interface WebGLContextEventInit extends EventInit { @@ -1646,10 +1858,17 @@ interface WorkletOptions { credentials?: RequestCredentials; } +interface txAuthGenericArg { + content: ArrayBuffer; + contentType: string; +} + interface EventListener { (evt: Event): void; } +type XPathNSResolver = ((prefix: string | null) => string | null) | { lookupNamespaceURI(prefix: string | null): string | null; }; + /** The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. */ interface ANGLE_instanced_arrays { drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; @@ -1658,15 +1877,14 @@ interface ANGLE_instanced_arrays { readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; } -/** The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired. */ +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ interface AbortController { /** * Returns the AbortSignal object associated with this object. */ readonly signal: AbortSignal; /** - * Invoking this method will set this object's AbortSignal's aborted flag and - * signal to any observers that the associated activity is to be aborted. + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ abort(): void; } @@ -1680,11 +1898,10 @@ interface AbortSignalEventMap { "abort": Event; } -/** The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ interface AbortSignal extends EventTarget { /** - * Returns true if this AbortSignal's AbortController has signaled to abort, and false - * otherwise. + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ readonly aborted: boolean; onabort: ((this: AbortSignal, ev: Event) => any) | null; @@ -1700,10 +1917,25 @@ declare var AbortSignal: { }; interface AbstractRange { + /** + * Returns true if range is collapsed, and false otherwise. + */ readonly collapsed: boolean; + /** + * Returns range's end node. + */ readonly endContainer: Node; + /** + * Returns range's end offset. + */ readonly endOffset: number; + /** + * Returns range's start node. + */ readonly startContainer: Node; + /** + * Returns range's start offset. + */ readonly startOffset: number; } @@ -1732,7 +1964,7 @@ interface AesCmacParams extends Algorithm { length: number; } -/** The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. */ +/** A node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. */ interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1801,7 +2033,7 @@ declare var AnimationEffect: { new(): AnimationEffect; }; -/** The AnimationEvent interface represents events providing information related to animations. */ +/** Events providing information related to animations. */ interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1813,6 +2045,11 @@ declare var AnimationEvent: { new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent; }; +interface AnimationFrameProvider { + cancelAnimationFrame(handle: number): void; + requestAnimationFrame(callback: FrameRequestCallback): number; +} + interface AnimationPlaybackEvent extends Event { readonly currentTime: number | null; readonly timelineTime: number | null; @@ -1839,7 +2076,7 @@ interface ApplicationCacheEventMap { "error": Event; "noupdate": Event; "obsolete": Event; - "progress": ProgressEvent; + "progress": ProgressEvent; "updateready": Event; } @@ -1857,7 +2094,7 @@ interface ApplicationCache extends EventTarget { /** @deprecated */ onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; /** @deprecated */ - onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; /** @deprecated */ onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; /** @deprecated */ @@ -1891,7 +2128,7 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; -/** This type represents a DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. */ +/** A DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. */ interface Attr extends Node { readonly localName: string; readonly name: string; @@ -1907,7 +2144,7 @@ declare var Attr: { new(): Attr; }; -/** Objects of these types are designed to hold small audio snippets, typically less than 45 s. For longer sounds, objects implementing the MediaElementAudioSourceNode are more suitable. The buffer contains data in the following format:  non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. If the AudioBuffer has multiple channels, they are stored in separate buffer. */ +/** A short audio asset residing in memory, created from an audio file using the AudioContext.decodeAudioData() method, or from raw data using AudioContext.createBuffer(). Once put into an AudioBuffer, the audio can then be played by being passed into an AudioBufferSourceNode. */ interface AudioBuffer { readonly duration: number; readonly length: number; @@ -1923,7 +2160,7 @@ declare var AudioBuffer: { new(options: AudioBufferOptions): AudioBuffer; }; -/** The AudioBufferSourceNode interface is an AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It's especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. */ +/** An AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It's especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. */ interface AudioBufferSourceNode extends AudioScheduledSourceNode { buffer: AudioBuffer | null; readonly detune: AudioParam; @@ -1943,7 +2180,7 @@ declare var AudioBufferSourceNode: { new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode; }; -/** The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an AudioNode. */ +/** An audio-processing graph built from audio modules linked together, each represented by an AudioNode. */ interface AudioContext extends BaseAudioContext { readonly baseLatency: number; readonly outputLatency: number; @@ -1953,6 +2190,7 @@ interface AudioContext extends BaseAudioContext { createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; createMediaStreamTrackSource(mediaStreamTrack: MediaStreamTrack): MediaStreamTrackAudioSourceNode; getOutputTimestamp(): AudioTimestamp; + resume(): Promise; suspend(): Promise; addEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -1975,7 +2213,7 @@ declare var AudioDestinationNode: { new(): AudioDestinationNode; }; -/** The AudioListener interface represents the position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. */ +/** The position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. */ interface AudioListener { readonly forwardX: AudioParam; readonly forwardY: AudioParam; @@ -1997,7 +2235,7 @@ declare var AudioListener: { new(): AudioListener; }; -/** The AudioNode interface is a generic interface for representing an audio processing module. Examples include: */ +/** A generic interface for representing an audio processing module. Examples include: */ interface AudioNode extends EventTarget { channelCount: number; channelCountMode: ChannelCountMode; @@ -2051,7 +2289,7 @@ declare var AudioParamMap: { new(): AudioParamMap; }; -/** The Web Audio API AudioProcessingEvent represents events that occur when a ScriptProcessorNode input buffer is ready to be processed. */ +/** The Web Audio API events that occur when a ScriptProcessorNode input buffer is ready to be processed. */ interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; readonly outputBuffer: AudioBuffer; @@ -2082,7 +2320,7 @@ declare var AudioScheduledSourceNode: { new(): AudioScheduledSourceNode; }; -/** The AudioTrack interface represents a single audio track from one of the HTML media elements,